phparraysstringstring-matchingarray-key-exists

Search a string using keys from an array and return the value of the first qualifying key


I have an array like this:

$array = ['cat' => 0, 'dog' => 1];

I have a string like this:

$string = 'I like cats.';

I want to see if any keys in the array are found in the string; if so, I want to return the value associated with the first matched key.

I tried 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 letters like vbncatnm. I am getting the array from a mysql database and I need to know which ID "cat" or "dog" is.


Solution

  • You can use a regex to check if the key is found in the string. The preg_match function allows to test a regular expression.

    $array = ['cat' => 0, 'dog' => 1];
    $string = 'I like cats';
    foreach ($array as $key => $value) {
        //If the key is found, prints the value and breaks
        if (preg_match("/".preg_quote($key, '/')."/", $string)) {
            echo $value . PHP_EOL;
            break;
        }
    }
    

    EDIT:

    As said in comment, strpos could be better! So, using the same code, you can just replace preg_match:

    $array = ['cat' => 0, 'dog' => 1];
    $string = 'I like cats';
    foreach ($array as $key => $value) {
        //If the key is found, prints the value and breaks
        if (false !== strpos($string, $key)) {
            echo $value . PHP_EOL;
            break;
        }
    }