[英]PHP Check if array element exists in any part of the string
我知道如何查找您的字符串是否等于数组值:
$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)) {
还是真的;)
只需循环包含值的数组,并使用strpos
检查它们是否在输入字符串中找到
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
foreach ( $colors as $c ) {
if ( strpos ( $string , $c ) !== FALSE ) {
echo "found";
}
}
您可以将其包装在一个函数中:
function findString($array, $string) {
foreach ( $array as $a ) {
if ( strpos ( $string , $a ) !== FALSE )
return true;
}
return false;
}
var_dump( findString ( $colors , "whitewash" ) ); // TRUE
没有内置功能,但是您可以执行以下操作:
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!preg_match('/\Q'.implode('\E|\Q',$colors).'\E/',$string)) {
echo 'not found';
}
这基本上是从您的数组中生成一个正则表达式,并将字符串与之匹配。 好的方法,除非您的数组非常大。
试试这个可行的解决方案
$colors = array("blue", "red", "white");
$string = "whitewash";
foreach ($colors as $color) {
$pos = strpos($string, $color);
if ($pos === false) {
echo "The string '$string' not having substring '$color'.<br>";
} else {
echo "The string '$string' having substring '$color'.<br>";
}
}
您将必须遍历每个数组元素,并分别检查它是否包含它(或它的一个substr)。
这类似于您要执行的操作: php检查字符串是否包含数组中的值
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
$hits = array();
foreach($colors as $color) {
if(strpos($string, $color) !== false) {
$hits[] = $color;
}
}
$ hits将包含在$ string中具有匹配项的所有$ colors。
if(empty($hits)) {
echo 'not found';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.