PHP code:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (in_array($search, $array)) {
echo "success";
}
else
echo "fail";
I want the success output. How is it possible?
You can use array_reduce
and stripos
to check all the values in $array
to see if they are present in $search
in a case-insensitive manner:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false))
echo "success";
else
echo "fail";
Output:
success
Edit
Since this is probably more useful wrapped in a function, here's how to do that:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
function search($array, $search) {
return array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false);
}
if (search($array, $search))
echo "success";
else
echo "fail";
$search2 = "michael";
if (search($array, $search2))
echo "success";
else
echo "fail";
Output
success
success
Here's an in_array
-esque function that will ignore case and bail early on a match:
function search_array($search, $arr) {
foreach ($arr as $item) {
if (stripos($search, $item) !== false) {
return 1;
}
}
return 0;
}
$search = "Who is KMichaele test";
$array = ["john", "michael", "adam"];
if (search_array($search, $array)) {
echo "success
";
}
else {
echo "fail
";
}
success
And here's a repl.
You can do this with a simple regx
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
$regex = '/\b('.implode('|', $array).')\b/i';
///\b(john|michael|adam)\b/i
$success = preg_match($regex, $search);
The Regex is simple
| or
the flag \i, case insensitive
Essential match any of the words in the list.
By using the boundary the word michael
will not match kmichael
for example. If you want partial word matches, just remove those.
Sandbox without the word boundry
If you include the 3rd argument
$success = preg_match($regex, $search,$match);
You can tell what the matches were. And last but not lest you can reduce it down to one line
$success = preg_match('/\b('.implode('|', $array).')\b/i', $search);