如何在PHP中查找数组中的字符串?

svmlkihl  于 11个月前  发布在  PHP
关注(0)|答案(6)|浏览(114)

我有一个数组:

$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";
}


是否正确?如果数组变大,会不会很慢?有没有其他方法?我正在尝试缩减数据库流量。
如果我有两个或多个字符串要比较,我该怎么做呢?

wwodge7n

wwodge7n1#

bool in_array  ( mixed $needle  , array $haystack  [, bool $strict  ] )

字符串
http://php.net/manual/en/function.in-array.php

x0fgdtte

x0fgdtte2#

如果你只需要一个精确的匹配,使用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;
   }
}

字符串

xhv8bpkk

xhv8bpkk3#

preg_match需要一个字符串输入,而不是一个数组。如果你使用你描述的方法,你将收到:
警告:preg_match()期望参数2是字符串,数组在X行的LOCATION中给出
你想要的in_array:

if ( in_array ( $str , $array ) ) {
    echo 'It exists';
} else {
    echo 'Does not exist';
}

字符串

fzwojiic

fzwojiic4#

为什么不使用_array中的内置函数?(http://www.php.net/in_array
preg_match仅在另一个字符串中查找子字符串时有效。(source

y53ybaqx

y53ybaqx5#

如果你有多个值,你可以分别测试每个值:

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
}

kyks70gy

kyks70gy6#

函数in_array()只检测数组元素的完整条目。如果您希望检测数组中的部分字符串,则必须检查每个元素。

foreach ($array AS $this_string) {
  if (preg_match("/(!)/", $this_string)) {
    echo "It exists"; 
  }
}

字符串

相关问题