【问题标题】:Search some text in PHP array在 PHP 数组中搜索一些文本
【发布时间】:2017-03-18 14:51:27
【问题描述】:

如何在 PHP 数组中搜索单词?

我尝试in_array,但它发现的值完全相同。

<?php
$namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');  
if (in_array('Peter Parker', $namesArray)) {echo "There is.";}
else {echo "There is not.";}

我希望这个实例返回 true。我该怎么做?有什么功能吗?

片段:https://glot.io/snippets/ek086tekl0

【问题讨论】:

    标签: php arrays search


    【解决方案1】:

    分解你的字符串,然后检查两个数组中是否有任何相同的字符串。

    $namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');
    if (array_intersect(explode(' ', 'Peter Parker'), $namesArray))
        echo "There is.";
    else
        echo "There is not.";
    

    【讨论】:

    • 感谢您提供可接受且简单的解决方案。我认为@Xorifelse 的解决方案更好。
    【解决方案2】:

    您可以使用正则表达式 - preg_match('i' 表示不区分大小写)来检查数组是否包含某些单词

    例如:

    $namesArray = array('Peter One', 'Other Peter', 'Glenn', 'Cleveland');
    $check = false;
    
    foreach($namesArray as $name) 
    {
        if (preg_match("/.*peter.*/i", $name)) {
            $check = true;
            break;
        }
    }
    
    if($check) 
    {
        echo "There is.";
    }
    else {
        echo "There is not.";
    }
    

    【讨论】:

    • 谢谢。 preg_match是个不错的方法,但是如果没有循环就更好了。
    【解决方案3】:

    我不得不说我喜欢 Gre_gor 的 answer 的简单性,但是对于更动态的方法你也可以使用 array_filter()

    function my_array_search($array, $needle){
      $matches = array_filter($array, function ($haystack) use ($needle){
        // return stripos($needle, $haystack) !== false; make the function case insensitive
        return strpos($needle, $haystack) !== false;
      });
    
      return empty($matches) ? false : $matches;
    }
    
    
    $namesArray = ['Peter', 'Glenn', 'Meg', 'Griffin'];
    

    示例:

    if(my_array_search($namesArray, 'Glenn Quagmire')){
       echo 'There is'; // Glenn
    } else {
       echo 'There is not';
    }
    
    // optionally:
    if(($retval = my_array_search($namesArray, 'Peter Griffin'))){
       echo 'There is';
       print_r($retval); // Peter, Griffin.
    } else {
       echo 'There is not';
    }
    

    现在$retval 是可选的,它捕获一组匹配的主题。这是因为如果my_array_search 中的$matches 变量为空,它会返回false 而不是空数组。

    【讨论】:

    • 感谢您的解决方案。在更改 $haystack$needle 变量的位置后,它就像我想要的那样工作。
    • @MertS.Kaplan 啊是的,我也会更新代码。
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多