Kei*_* C. 3 php database string pattern-matching array-key-exists
我做了很多搜索,但无法弄清楚这个.
我有这样一个数组:
$array = array(cat => 0, dog => 1);
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的字符串:
I like cats.
Run Code Online (Sandbox Code Playgroud)
我想看看字符串是否匹配数组中的任何键.我尝试以下但显然它不起作用.
array_key_exists("I like cats", $array)
Run Code Online (Sandbox Code Playgroud)
假设我可以在给定时间获得任何随机字符串,我该怎么做这样的事情?
伪代码:
array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"
Run Code Online (Sandbox Code Playgroud)
请注意,我想检查是否存在任何形式的"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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
正如评论中所说,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;
}
}
Run Code Online (Sandbox Code Playgroud)