繁体   English   中英

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

[英]PHP How to check if an array contains a pattern from another array

我正在寻找一个与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

}

使用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
)

请尝试以下代码:

<?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>");
?>

希望对您有帮助=}

您可以使用:

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

此函数在数组$arr的每个项目上调用一个您可以自定义的函数,在这种情况下,请检查您是否在另一个数组中

为什么不仅仅编写自己的代码/函数呢?

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.
}

我会去:

 $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 )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM