我有一个数组:
$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";
}
这是正确的方法吗?如果阵列变大,它会非常慢吗?还有其他方法吗?我正在尝试缩小数据库流量。
如果我要比较两个或更多字符串,我该怎么做?
答案 0 :(得分:34)
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
答案 1 :(得分:6)
如果您只需要完全匹配,请使用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;
}
}
答案 2 :(得分:4)
preg_match期望字符串输入不是数组。如果您使用您描述的方法,您将收到:
警告:preg_match()期望参数2为字符串,在第X行的LOCATION中给出的数组
你想要in_array:
if ( in_array ( $str , $array ) ) {
echo 'It exists';
} else {
echo 'Does not exist';
}
答案 3 :(得分:3)
为什么不使用内置函数in_array? (http://www.php.net/in_array)
preg_match仅在查找另一个字符串中的子字符串时才有效。 (source)
答案 4 :(得分:2)
如果您有多个值,则可以单独测试每个值:
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
}
答案 5 :(得分:0)
函数in_array()仅检测数组元素的完整条目。如果要检测数组中的部分字符串,则必须检查每个元素。
foreach ($array AS $this_string) {
if (preg_match("/(!)/", $this_string)) {
echo "It exists";
}
}