4

我做了一堆搜索,但无法弄清楚这个。

我有一个这样的数组:

$array = array(cat => 0, dog => 1);

我有一个这样的字符串:

I like cats.

我想看看字符串是否与数组中的任何键匹配。我尝试以下但显然它不起作用。

array_key_exists("I like cats", $array)

假设我可以在给定时间获得任何随机字符串,我该怎么做这样的事情?

伪代码:

array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"

请注意,我想检查是否存在任何形式的“猫”。它可以是猫,cathy,甚至是像 vbncatnm 这样的随机字母。我从 mysql 数据库中获取数组,我需要知道 cat 或 dog 是哪个 ID。

4

3 回答 3

7

您可以在键上使用正则表达式。因此,如果您的字符串中的任何单词等于键,$found则为true. 如果需要,您可以将 保存$key在变量中。preg_match函数允许测试正则表达式。

$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
    //If the key is found in your string, set $found to true
    if (preg_match("/".$key."/", "I like cats")) {
        $found = true;
    }
}

编辑 :

正如评论中所说,strpos可能会更好!因此,使用相同的代码,您只需替换 preg_match:

$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
    //If the key is found in your string, set $found to true
    if (false !== strpos("I like cats", $key)) {
        $found = true;
    }
}
于 2016-10-22T19:03:08.950 回答
1

这应该可以帮助您实现您想要做的事情:

$array         = array('cat' => 10, 'dog' => 1);

$findThis      = 'I like cats';

$filteredArray = array_filter($array, function($key) use($string){

    return strpos($string, $key) !== false;

}, ARRAY_FILTER_USE_KEY);

我发现使用带有闭包/匿名函数的 array_filter 函数比 foreach 循环更优雅,因为它保持了一级缩进。

于 2016-10-22T19:47:18.230 回答
0

您可以使用 preg_match 的值不在数组中而是在搜索条件中

 if(preg_match('~(cat|dog)~', "I like cats")) {
    echo 'ok';
}

或者

$criteria = '~(cat|dog)~';

 if (preg_match($criteria, "I like cats")) {
    echo 'ok';
}

否则,您可以在阵列上使用 foreach

 foreach($array as $key => $value ) {
     $pos = strpos("I like cats", $key);
     if ($pos > 0) {
      echo $key .  ' '. $value;
     }

 }
于 2016-10-22T18:48:34.377 回答