簡體   English   中英

PHP 檢查字符串數組是否包含子字符串數組中的任何值

[英]PHP Check if an array of strings contains any value from an array of substrings

例如。 我有 2 個 arrays:

$arr1 = array("cake", "make"); $arr2 = array("birthday cake", "maker", "a random index");

我想檢查$arr1的兩個值是否作為 substring 存在於$arr2中。 $arr2也可能有其他元素,但它是否包含$arr1的所有索引作為子字符串並不重要。

我知道標准的嵌套循環方法,但我不想使用它,因為性能會很糟糕(因為我有一個大數組)。 我想問一下 PHP 是否包含內置的 function ,或者是否有另一種方法可以以更好的時間復雜度完成此任務[最好是 O(log n),但 O(n) 也可以]。

如果你說你有一個大數組要檢查,優化 arrays 的處理。

  1. 一旦您在 arr1 中找不到其中一項,它就會全部終止並返回 false
  2. 通過引用傳遞數組參數,因此無需將 arrays 復制到堆棧
  3. 將最有可能在 arr2 中找不到的東西放在 arr1 的開頭
$arr1 = array( "cake", "make");
$arr2 = array("birthday cake", "maker", "a random index");

// pass arrays by reference, so you dont have to create copies 
// of large arrays on to the stack
function testThem(&$arr1, &$arr2) {
    // as soon as a unfound situation is indicated, return from the function with false
    foreach ($arr1 as $a1) {
        $found = false;
        foreach ($arr2 as $a2) {
            if (strpos($a2, $a1) !== false) {
                //as soon as a found occurs break out of this foreach
                $found = true;
                break;
            }
        }
        // If we get here with a $found still = false
        // we didnt find one of the things in $arr1 within $arr2 
        // so no more looping required. Finish and return false
        if (!$found) { 
            return false;
        }
    }    
    // only if we find all the items do we eventually get here after lots of loops
    return true;
}


if ( testThem($arr1, $arr2) ) {
    echo 'All Found';
} else {
    echo 'Something not found';
}

如果我們制作第二個數組的字符串

$arr2 = implode('###',$arr2);

然后使用 array_filter 如下:

$result = array_filter($arr1,function($value) use($arr2){
    return (strpos($value,$arr2)!==false)?$value:false;
});

print_r(array_filter($result));

這里我們有來自 $arr1 的所有匹配子字符串。

我認為嵌套循環是唯一的方法,但是一旦確定答案,就可以更有效地跳出循環。

$found_all = true;
foreach ($arr1 as $str1) {
    $found1 = false;
    foreach ($arr2 as $str2) {
        if (strpos($str2, $str1) !== false) {
            $found1 = true;
            break;
        }
    }
    if (!$found1) {
        $found_all = false;
        break;
    }
}
echo $found_all ? "All found" : "Not all found";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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