我有一个数组:
$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";
}
型
是否正确?如果数组变大,会不会很慢?有没有其他方法?我正在尝试缩减数据库流量。
如果我有两个或多个字符串要比较,我该怎么做呢?
6条答案
按热度按时间wwodge7n1#
字符串
http://php.net/manual/en/function.in-array.php
x0fgdtte2#
如果你只需要一个精确的匹配,使用in_array($str,$array)--它会更快。
另一种方法是使用一个关联数组,将字符串作为键,这应该在编程上更快。不过,你可能会看到这与只有80个元素的线性搜索方法之间的巨大差异。
如果你确实需要模式匹配,那么你需要循环遍历数组元素来使用preg_match。
你编辑了这个问题,询问“如果你想检查多个字符串怎么办?”-你需要循环这些字符串,但是你可以在没有匹配的时候停止。
字符串
xhv8bpkk3#
preg_match需要一个字符串输入,而不是一个数组。如果你使用你描述的方法,你将收到:
警告:preg_match()期望参数2是字符串,数组在X行的LOCATION中给出
你想要的in_array:
字符串
fzwojiic4#
为什么不使用_array中的内置函数?(http://www.php.net/in_array)
preg_match仅在另一个字符串中查找子字符串时有效。(source)
y53ybaqx5#
如果你有多个值,你可以分别测试每个值:
字符串
或者你可以对字符串和数组都做一个intersection:
型
kyks70gy6#
函数in_array()只检测数组元素的完整条目。如果您希望检测数组中的部分字符串,则必须检查每个元素。
字符串