簡體   English   中英

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"; // 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM