Matching an Exact String within a String - php

I'm having a problem that the code is returning "Men" for all of the "Women" values because it also contains the term "Men." I've tried "~\bWord\b~" in vain.
How can the code below be edited to return different values?
function replaceWords($value) {
//here are predefined values
$predefined = array(
array(
'search'=>'Women',
'replaceWith'=>'Women'
),
array(
'search'=>'Men',
'replaceWith'=>'Men'
)
);
//search and replace
$found = false;
foreach ($predefined as $item) {
$search = array_map('trim', explode(',', $item['search']));
foreach ($search as $s) {
if (strstr(strtolower($value), strtolower($s))) {
$found = true;
$value = $item['replaceWith'];
break;
}
}
}
return ($found)?$value:"";
}
Help is much appreciated.

simply don't use strtolower()
"Women" and "Men" won't match if you keep it case sensitive.

This worked for me:
if (preg_match("/\b".strtolower($s)."\b/i", strtolower($value)) ) {

Related

How to get the values only if all the keys have matched?

I want to make a method that returns keys and values. But only if the keys include the following string "_1" and "__last".
If only one matches then exit the function, only if the two string are included in the key, return the key with the value for a weather.
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny",
"humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"))
public function getData() {
$list = array();
foreach($infoList as $key){
if(preg_match('/(_key)_(_1)/', $key) && preg_match('/(_key)_(__last)/', $key) == TRUE){
$list[$key] = $list[$key]["weather"]
}
}
return $list
}
You are making your life so much more difficult that it need be, use str_contains() its easier than building complex REGEX's and getting very confused by the look of it :)
I also fixed a number of other mistakes, such as the foreach that was not going to work, so check all the code.
It is also better to pass data to a function/method otherwise you get into scoping issues!
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny", "humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"));
function getData(Array $infoList) {
$list = [];
$found = 0;
foreach($infoList as $key => $val) {
if( str_contains($key, '_1') || str_contains($key, '__last') ) {
$list[$key] = $val["weather"];
$found++;
}
}
if ( $found >= 2 ) {
return $list;
} else {
return false;
}
}
$res = getData($infoList);
if ( $res !== false ){
print_r($res);
} else {
echo 'Not Found';
}
RESULTS
Array
(
[_key_1] => sunny
[_key__last] => rainy
)
If you want to stick with RegEx, you can use positive lookaheads, the same way you check for passwords characters :
<?php
$pattern = '/^(?=.*_1)(?=.*_last).*$/';
$shouldMatch = [
'_1_last',
'foo_1bar_lasthello',
'_last_1',
'foo_lastbar_1hello'
];
echo 'next ones should match : ' . PHP_EOL;
foreach ($shouldMatch as $item)
{
if (preg_match($pattern, $item))
echo $item . PHP_EOL;
}
$shouldNOTMatch = [
'_2_first',
'bar_lasthello',
'foo_las_1hello'
];
echo 'next ones should NOT match : ' . PHP_EOL;
foreach ($shouldNOTMatch as $item)
{
// v------------ check
if (!preg_match($pattern, $item))
echo $item . PHP_EOL;
}
Output :
next ones should match :
_1_last
foo_1bar_lasthello
_last_1
foo_lastbar_1hello
next ones should NOT match :
_2_first
bar_lasthello
foo_las_1hello

PHP get possible string combination of given array which match with given string

I have an array which contains bunch of strings, and I would like to find all of the possible combinations no matter how it's being sorted that match with given string/word.
$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];
input: stackoverflow
output:
#1 -> ['stack', 'over', 'flow']
#2 -> ['stackover', 'flow']
What I've tried is, I need to exclude the array's element which doesn't contain in an input string, then tried to match every single merged element with it but I'm not sure and get stuck with this. Can anyone help me to figure the way out of this? thank you in advance, here are my code so far
<?php
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$word = 'stackoverflow';
$dictHas = [];
foreach ($dict as $w) {
if (strpos($word, $w) !== false) {
$dictHas[] = $w;
}
}
$result = [];
foreach ($dictHas as $el) {
foreach ($dictHas as $wo) {
$merge = $el . $wo;
if ($merge == $word) {
} elseif ((strpos($word, $merge) !== false) {
}
}
}
print_r($result);
For problems like this you want to use backtracking
function splitString($string, $dict)
{
$result = [];
//if the string is already empty return empty array
if (empty($string)) {
return $result;
}
foreach ($dict as $idx => $term) {
if (strpos($string, $term) === 0) {
//if the term is at the start of string
//get the rest of string
$substr = substr($string, strlen($term));
//if all of string has been processed return only current term
if (empty($substr)) {
return [[$term]];
}
//get the dictionary without used term
$subDict = $dict;
unset($subDict[$idx]);
//get results of splitting the rest of string
$sub = splitString($substr, $subDict);
//merge them with current term
if (!empty($sub)) {
foreach ($sub as $subResult) {
$result[] = array_merge([$term], $subResult);
}
}
}
}
return $result;
}
$input = "stackoverflow";
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$output = splitString($input, $dict);

remove value from array what the words is not fully match

How i can remove a value from array what is not fully match the letters.
Array code example:
$Array = array(
'Funny',
'funnY',
'Games',
);
How I can unset all values from this array what is 'funny'
I try via unset('funny'); but is not removing the values from array, is removed just if i have 'funny' on array but 'funnY' or 'Funny' not working
Maybe there is some sophisticated solution with array_intersect_key or something which could do this in one line but I assume this approach is more easily read:
function removeCaseInsensitive($array, $toRemove) {
$ret = [];
foreach ($array as $v) {
if (strtolower($v) != strtolower($toRemove))
$ret[] = $v;
}
return $ret;
}
This returns a new array that does not contain any case of $toRemove. If you want to keep the keys than you can do this:
function removeCaseInsensitive($array, $toRemove) {
$keep = [];
foreach ($array as $k => $v) {
if (strtolower($v) != strtolower($toRemove))
$keep[$k] = true;
}
return array_intersect_keys($array, $keep);
}
You can filter out those values with a loose filtering rule:
$array = array_filter($array, function($value) {
return strtolower($value) !== 'funny';
});

PHP array_key_exists key LIKE string, is it possible?

I've done a bunch of searching but can't figure this one out.
I have an array like this:
$array = array(cat => 0, dog => 1);
I have a string like this:
I like cats.
I want to see if the string matches any keys in the array. I try the following but obviously it doesn't work.
array_key_exists("I like cats", $array)
Assuming that I can get any random string at a given time, how can I do something like this?
Pseudo code:
array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"
Note that I want to check if "cat" in any form exists. It can be cats, cathy, even random letter like vbncatnm. I am getting the array from a mysql database and I need to know which ID cat or dog is.
You can use a regex on keys. So, if any words of your string equal to the key, $found is true. You can save the $key in the variable if you want. preg_match function allows to test a regular expression.
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (preg_match("/".$key."/", "I like cats")) {
$found = true;
}
}
EDIT :
As said in comment, strpos could be better! So using the same code, you can just replace preg_match:
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (false !== strpos("I like cats", $key)) {
$found = true;
}
}
This should help you achieve what you're trying to do:
$array = array('cat' => 10, 'dog' => 1);
$findThis = 'I like cats';
$filteredArray = array_filter($array, function($key) use($string){
return strpos($string, $key) !== false;
}, ARRAY_FILTER_USE_KEY);
I find that using the array_filter function with a closure/anonymous function to be a much more elegant way than a foreach loop because it maintains one level of indentation.
You could do using a preg_match with the value not in array but in search criteria
if(preg_match('~(cat|dog)~', "I like cats")) {
echo 'ok';
}
or
$criteria = '~(cat|dog)~';
if (preg_match($criteria, "I like cats")) {
echo 'ok';
}
Otherwise you could use a foreach on your array
foreach($array as $key => $value ) {
$pos = strpos("I like cats", $key);
if ($pos > 0) {
echo $key . ' '. $value;
}
}

PHP Array values in string?

I have been looking around for a while in the PHP manual and can't find any command that does what I want.
I have an array with Keys and Values, example:
$Fields = array("Color"=>"Bl","Taste"=>"Good","Height"=>"Tall");
Then I have a string, for example:
$Headline = "My black coffee is cold";
Now I want to find out if any of the array ($Fields) values match somewhere in the string ($Headline).
Example:
Array_function_xxx($Headline,$Fields);
Would give the result true because "bl" is in the string $Headline (as a part of "Black").
I'm asking because I need performance... If this isn't possible, I will just make my own function instead...
EDIT - I'm looking for something like stristr(string $haystack , array $needle);
Thanks
SOLUTION - I came up with his function.
function array_in_str($fString, $fArray) {
$rMatch = array();
foreach($fArray as $Value) {
$Pos = stripos($fString,$Value);
if($Pos !== false)
// Add whatever information you need
$rMatch[] = array( "Start"=>$Pos,
"End"=>$Pos+strlen($Value)-1,
"Value"=>$Value
);
}
return $rMatch;
}
The returning array now have information on where each matched word begins and ends.
This should help:
function Array_function_xxx($headline, $fields) {
$field_values = array_values($fields);
foreach ($field_values as $field_value) {
if (strpos($headline, $field_value) !== false) {
return true; // field value found in a string
}
}
return false; // nothing found during the loop
}
Replace name of the function with what you need.
EDIT:
Ok, alternative solution (probably giving better performance, allowing for case-insensitive search, but requiring proper values within $fields parameter) is:
function Array_function_xxx($headline, $fields) {
$regexp = '/(' . implode('|',array_values($fields)) . ')/i';
return (bool) preg_match($regexp, $headline);
}
http://www.php.net/manual/en/function.array-search.php
that's what you looking for
example from php.net
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

Categories