【问题标题】:Compare string against array of strings in PHP?将字符串与PHP中的字符串数组进行比较?
【发布时间】:2012-01-17 09:02:25
【问题描述】:

我有一个类似abcdefg123hijklm 的字符串。我还有一个包含多个字符串的数组。现在我想检查我的abcdefg123hijklm 并查看来自abcdefg123hijklm123 是否在数组中。我怎样才能做到这一点?我猜in_array() 不会工作?

谢谢?

【问题讨论】:

    标签: php arrays string


    【解决方案1】:

    所以您想检查该特定字符串的任何子字符串(我们称之为$searchstring)是否在数组中? 如果是这样,您将需要遍历数组并检查子字符串:

    foreach($array as $string)
    {
      if(strpos($searchstring, $string) !== false) 
      {
        echo 'yes its in here';
        break;
      }
    }
    

    见:http://php.net/manual/en/function.strpos.php

    如果要检查字符串的特定部分是否在数组中,则需要使用substr() 分隔字符串的该部分,然后使用in_array() 查找它。

    http://php.net/manual/en/function.substr.php

    【讨论】:

    • 我会将echo 部分放在代码块(大括号)中,并在右大括号之前添加一个break; - 当您只需要知道是否至少有一个时有助于提高性能字符串匹配。
    【解决方案2】:

    另一种选择是使用正则表达式和内爆,如下所示:

    if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
        echo("Yes, the string '{$matches[0]}' was found in the search string.");
    else
        echo("None of the strings in the array were found in the search string.");
    

    它的代码少了一点,我希望它对大型搜索字符串或数组更有效,因为搜索字符串只需解析一次,而不是对数组的每个元素解析一次。 (虽然你确实增加了内爆的开销。)

    一个缺点是它不返回匹配字符串的数组索引,因此如果需要,循环可能是更好的选择。但是,您也可以使用上面的代码找到它,然后

    $match_index = array_search($matches[0], $array);
    

    编辑:请注意,这假设您知道您的字符串不会包含正则表达式特殊字符。对于像您的示例这样的纯字母数字字符串,这将是正确的,但是如果您要拥有更复杂的字符串,则必须首先对其进行转义。在这种情况下,使用循环的其他解决方案可能会更简单。

    【讨论】:

      【解决方案3】:

      你可以反过来做。假设你的字符串是 $string 而数组是 $array。

      foreach ($array as $value)
      {
          // strpos can return 0 as a first matched position, 0 == false but !== false
          if (strpos($string, $value) !== false)
          {
              echo 'Matched value is ' . $value;
          }  
      } 
      

      【讨论】:

      • 这并不总是有效,因为如果在 $str strpos() 的开头找到 $value 将返回 0,其评估结果为 false
      【解决方案4】:

      用它来获取你的号码

      $re = "/(\d+)/";
      $str = "abcdefg123hijklm";
      
      preg_match($re, $str, $matches);
      

      and ( 123 可以是上面的 $matches[1] ):

         preg_grep('/123/', $array);
      

      http://www.php.net/manual/en/function.preg-grep.php

      【讨论】:

        最近更新 更多