编程语言
首页 > 编程语言> > PHP array_key_exists键LIKE字符串,是否可能?

PHP array_key_exists键LIKE字符串,是否可能?

作者:互联网

我做了很多搜索,但无法弄清楚这个.

我有这样一个数组:

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

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

解决方法:

您可以在键上使用正则表达式.因此,如果您的字符串中的任何单词等于键,则$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;
    }
}

标签:php,string,pattern-matching,database,array-key-exists
来源: https://codeday.me/bug/20190828/1755527.html