我知道如何查找您的字符串是否等于数组值:
$colors = array("blue","red","white");
$string = "white";
if (!in_array($string, $colors)) {
echo 'not found';
}
...但是我如何找到字符串是否包含数组值的任何部分?
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!in_array($string, $colors)) {
echo 'not found';
}
最佳答案
或者一次性:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")",$string,$m)) {
echo "Found ".$m[0]."!";
}
这也可以扩展为仅允许以数组中的项目开头的单词:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))",$string,$m)) {
或不区分大小写:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")i",$string,$m)) {
仅开始的 CI:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))i",$string,$m)) {
或者任何真的;)
关于PHP 检查字符串的任何部分是否存在数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25229364/