PHP如何检查数组是否包含来自另一个数组的模式

时间:2017-04-04 19:05:53

标签: php arrays preg-grep

我正在寻找一种与in_array相同的替代函数,但也可以检查搜索词是否只包含给定元素的一部分而不是整个元素:

目前使用以下脚本:

$attributes = array('dogs', 'cats', 'fish');

  if (in_array($attributes, array('dog','cats','fishess'), true )) {

    * does something for cats, but not for dogs and fish
      because the function only checks if the given term is identical to the word in the array instead of only a part of the word *
} 

我如何构建我的up函数,以便它传递仅包含数组中部分单词的单词?

首选示例如下所示:

$words = array('fish', 'sharks');

if (*word or sentence part is* in_array($words, array('fishing', 'sharkskin')){

return 'your result matched 2 elements in the array $words

}

5 个答案:

答案 0 :(得分:1)

使用array_filterpreg_grep函数的解决方案:

$words = ['fish', 'sharks', 'cats', 'dogs'];
$others = ['fishing', 'sharkskin'];

$matched_words = array_filter($words, function($w) use($others){
    return preg_grep("/" . $w . "/", $others);
});

print_r($matched_words);

输出:

Array
(
    [0] => fish
    [1] => sharks
)

答案 1 :(得分:1)

尝试以下代码:

<?php
$what  = ['fish', 'sharks'];
$where = ['fishing', 'sharkskin'];

foreach($what as $one)
    foreach($where as $other)
        echo (strpos($other, $one)!==false ? "YEP! ".$one." is in ".$other."<br>" : $one." isn't in ".$other."<br>");
?>

希望有帮助=}

答案 2 :(得分:0)

你可以使用:

array_filter($arr, function($v, $k) {
    // do whatever condition you want
    return in_array($v, $somearray);
}, ARRAY_FILTER_USE_BOTH);

这个函数调用数组$arr中的每个项目,你可以自定义一个函数,在你的情况下检查你是否在另一个数组中元素

答案 3 :(得分:0)

为什么不制作自己的代码/功能?

foreach ($item in $attributes) {
    foreach ($item2 in array('dog','cats','fishess')) {
        // Check your custom functionality.
        // Do something if needed.
    }
}

您可以查看array_intersect,但它不会检查模式匹配(您以某种方式提到过吗?)

  

array_intersect()返回一个数组,其中包含所有参数中存在的array1的所有值。请注意,密钥会被保留。

foreach (array_intersects($attributes, array('dog','cats','fishess') {
    // do something.
}

答案 4 :(得分:0)

我会选择:

 $patterns = array('/.*fish.*/', '/.*sharks.*/'); 
 $subjects = array('fishing', 'aaaaa', 'sharkskin');
 $matches = array();
 preg_replace_callback(
    $patterns,
    function ($m) {
        global $matches;
        $matches[] =  $m[0];
        return $m[0];
    },
    $subjects
 );

 print_r($matches); // Array ( [0] => fishing [1] => sharkskin )