douhong9210 2016-10-22 18:42
浏览 154
已采纳

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

I've done a bunch of searching but can't figure this one out.

I have an array like this:

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

I have a string like this:

I like cats.

I want to see if the string matches any keys in the array. I try the following but obviously it doesn't work.

array_key_exists("I like cats", $array)

Assuming that I can get any random string at a given time, how can I do something like this?

Pseudo code:

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

Note that I want to check if "cat" in any form exists. It can be cats, cathy, even random letter like vbncatnm. I am getting the array from a mysql database and I need to know which ID cat or dog is.

  • 写回答

3条回答 默认 最新

  • drza10046 2016-10-22 19:03
    关注

    You can use a regex on keys. So, if any words of your string equal to the key, $found is true. You can save the $key in the variable if you want. preg_match function allows to test a regular expression.

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

    EDIT :

    As said in comment, strpos could be better! So using the same code, you can just replace 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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c