【问题标题】:How to find a string in an array in PHP?如何在 PHP 中的数组中查找字符串?
【发布时间】:2009-02-17 08:46:02
【问题描述】:

我有一个数组:

$array = array("apple", "banana", "cap", "dog", etc..) up to 80 values.

还有一个字符串变量:

$str = "abc";

如果我想检查这个字符串($str)是否存在于数组中,我使用preg_match函数,它是这样的:

$isExists = preg_match("/$str/", $array);

if ($isExists) {
    echo "It exists";
} else {
    echo "It does not exist";
}

这是正确的方法吗?如果数组变大,会不会很慢?还有其他方法吗?我正在尝试缩减我的数据库流量。

如果我有两个或多个字符串要比较,我该怎么做?

【问题讨论】:

标签: php arrays


【解决方案1】:
 bool in_array  ( mixed $needle  , array $haystack  [, bool $strict  ] )

http://php.net/manual/en/function.in-array.php

【讨论】:

    【解决方案2】:

    如果您只需要完全匹配,请使用in_array($str, $array) - 它会更快。

    另一种方法是使用以字符串为键的关联数组,这应该在对数上更快。毫无疑问,您会发现这与只有 80 个元素的线性搜索方法之间存在巨大差异。

    如果您确实需要模式匹配,那么您需要遍历数组元素以使用 preg_match。


    您编辑了问题以询问“如果要检查多个字符串怎么办?” - 你需要遍历这些字符串,但是一旦没有匹配到你就可以停止...

    $find=array("foo", "bar");
    $found=count($find)>0; //ensure found is initialised as false when no terms
    foreach($find as $term)
    {
       if(!in_array($term, $array))
       {
            $found=false;
            break;
       }
    }
    

    【讨论】:

      【解决方案3】:

      preg_match 需要一个字符串输入而不是一个数组。如果您使用您描述的方法,您将收到:

      警告:preg_match() 期望参数 2 是字符串,在 X 行的 LOCATION 中给出的数组

      你想要 in_array:

      if ( in_array ( $str , $array ) ) {
          echo 'It exists';
      } else {
          echo 'Does not exist';
      }
      

      【讨论】:

      • 这样的字符串 $var "id1;id2";
      • Paul Dixon 上面的回答很好地回答了这个问题。
      【解决方案4】:

      为什么不使用内置函数 in_array? (http://www.php.net/in_array)

      preg_match 仅在查找另一个字符串中的子字符串时才有效。 (source)

      【讨论】:

        【解决方案5】:

        如果您有多个值,您可以分别测试每个值:

        if (in_array($str1, $array) && in_array($str2, $array) && in_array($str3, $array) /* … */) {
            // every string is element of the array
            // replace AND operator (`&&`) by OR operator (`||`) to check
            // if at least one of the strings is element of the array
        }
        

        或者你可以对字符串和数组都做一个intersection

        $strings = array($str1, $str2, $str3, /* … */);
        if (count(array_intersect($strings, $array)) == count($strings)) {
            // every string is element of the array
            // remove "== count($strings)" to check if at least one of the strings is element
            // of the array
        }
        

        【讨论】:

          【解决方案6】:

          函数 in_array() 仅检测数组元素的完整条目。如果您希望检测数组中的部分字符串,则必须检查每个元素。

          foreach ($array AS $this_string) {
            if (preg_match("/(!)/", $this_string)) {
              echo "It exists"; 
            }
          }
          

          【讨论】:

            猜你喜欢
            • 2017-03-22
            • 1970-01-01
            • 1970-01-01
            • 2020-06-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-20
            相关资源
            最近更新 更多