Keith C. Keith C. - 1 month ago 14
PHP Question

PHP array_key_exists key LIKE string, is it possible?

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.

Answer

You can use a regex on keys. So, if any word of your string equals to the key, $found is true. You can save the $key in the variable if you want. preg_match function allow to test a regulat 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;
    }
}
Comments