我有一个字符串abcdefg123hijklm.我还有一个包含几个字符串的数组.现在,我想看看我abcdefg123hijklm,看看123从abcdefg123hijklm是在数组中.我怎样才能做到这一点?我想in_array()不会工作?
谢谢?
bar*_*iir 11
所以你想检查那个特定字符串的任何子字符串(让我们调用它$searchstring)是否在数组中?如果是这样,您将需要迭代数组并检查子字符串:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅:http://php.net/manual/en/function.strpos.php
如果要检查String的特定部分是否在数组中,则需要使用它substr()来分隔字符串的该部分,然后使用in_array()它来查找它.
http://php.net/manual/en/function.substr.php
另一个选择是使用正则表达式和内爆,如下所示:
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.");
Run Code Online (Sandbox Code Playgroud)
它的代码少了一些,我希望它对大型搜索字符串或数组更有效,因为搜索字符串只需要解析一次,而不是一次解析数组的每个元素.(虽然你确实增加了内爆的开销.)
一个缺点是它不返回匹配字符串的数组索引,因此如果需要,循环可能是更好的选择.但是,您也可以使用上面的代码找到它
$match_index = array_search($matches[0], $array);
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,这假设您知道您的字符串不会包含正则表达式特殊字符.对于纯粹的字母数字字符串,例如你的例子,这将是真的,但如果你将有更复杂的字符串,你将不得不首先逃避它们.在这种情况下,使用循环的其他解决方案可能更简单.