Jake
Jake

Reputation: 240

Check if any word from a string is in an array (Case insensitive)

I hope this is not a duplicate, but I couldn't find something matching.

I'm getting the following response from an api:

Ingredients: Whey, Beef, Egg, Nuts

I'm using this as a string in my script, and now I want to check, if any of the words in the string match with my array. What I'm using right now is:

$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
              if ($i >= 1){
                echo "True";
              }
              else {
                echo "False";
              }

This works fine, but if the response is not Whey, Beef, Egg, Nuts but instead whey, beef, EGG, nuts this doesn't work anymore.

I then used this:

array_search(strtolower($string), array_map('strtolower', $array));

but this only works with one ingredient.

I would appreciate any help!

Upvotes: 1

Views: 199

Answers (1)

lukas.j
lukas.j

Reputation: 7173

You can use array_uintersect, which takes a comparison function in which you can do case-insensitive comparison with strcasecmp:

$response = 'Ingredients: Whey, bEEf, EgG, NuTs';

$items = array_map('trim', array_slice(preg_split('/[:,]/', $response), 1));

$array = [ 'Beef', 'Nuts'];

$result = array_uintersect($array, $items, fn($a, $b) => strcasecmp($a, $b));

print_r($result);

Upvotes: 2

Related Questions