Products
GG网络技术分享 2025-03-18 16:12 2
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?
图片转代码服务由CSDN问答提供
感谢您的意见,我们尽快改进~
功能建议PHP代码:</ p>
$ search =“谁是KMichaele 测试“; $ array = [”john“,”michael“,”adam“];
if(in_array($ search,$ array)){
echo”success“;
}
else
echo “失败”;
</ code> </ pre>
我想要成功输出。 怎么可能?</ p>
</ div>
网友观点:
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
successsuccess
###
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
\\\";
}
Output
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
- \\b - matches word boundary
| 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);
Demand feedback