我有一个数组:
$array = array("apple", "banana", "cap", "dog", etc..) up to 80 values.
Run Code Online (Sandbox Code Playgroud)
和一个字符串变量:
$str = "abc";
Run Code Online (Sandbox Code Playgroud)
如果我想检查$str数组中是否存在此字符串(),我使用的preg_match函数如下所示:
$isExists = preg_match("/$str/", $array);
if ($isExists) {
echo "It exists";
} else {
echo "It does not exist";
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?如果阵列变大,它会非常慢吗?还有其他方法吗?我试图缩小我的数据库流量.
如果我要比较两个或更多字符串,我该怎么做?
Sam*_*fee 34
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.in-array.php
如果你只需要一个完全匹配,使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
preg_match 需要一个字符串输入而不是一个数组。如果您使用您描述的方法,您将收到:
警告:preg_match() 期望参数 2 是字符串,数组在 X 行的 LOCATION 中给出
你想要 in_array:
if ( in_array ( $str , $array ) ) {
echo 'It exists';
} else {
echo 'Does not exist';
}
Run Code Online (Sandbox Code Playgroud)