将字符串与PHP中的字符串数组进行比较?

时间:2012-01-17 09:02:26

标签: php arrays string

我有一个像abcdefg123hijklm这样的字符串。我还有一个包含几个字符串的数组。现在,我想查看我的abcdefg123hijklm,看看来自123的{​​{1}}是否在数组中。我怎样才能做到这一点?我猜abcdefg123hijklm不会工作?

感谢?

4 个答案:

答案 0 :(得分:11)

所以你想检查那个特定字符串的任何子字符串(让我们称之为$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

答案 1 :(得分:7)

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

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

编辑:请注意,这假设您知道您的字符串不包含正则表达式特殊字符。对于纯粹的字母数字字符串,例如你的例子,这将是真的,但如果你将有更复杂的字符串,你将不得不首先逃避它们。在这种情况下,使用循环的其他解决方案可能会更简单。

答案 2 :(得分:2)

你可以反过来做。假设你的字符串是$ 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;
    }  
} 

答案 3 :(得分:1)

使用此功能获取您的号码

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

preg_match($re, $str, $matches);

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

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

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

相关问题