PHP 检查字符串的任何部分是否存在数组元素


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";       
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>";                
    }
}

没有内置函数,但您可以执行以下操作:

$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';
}

这基本上是从您的数组中创建一个正则表达式,并将字符串与其匹配。好方法,除非你的数组真的很大。

您必须遍历每个数组元素并单独检查它是否包含它(或它的子元素(。

这类似于您要执行的操作: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';
}