1

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!

Jake
  • 77
  • 6
  • Have the words in your array be lowercase to begin with (or convert them to that once), and then pass `strtolower($string)` to your nested preg_replace/explode call ...? – CBroe Feb 01 '22 at 10:32
  • I think what you need is a ```foreach``` loop. Maybe this helps: https://stackoverflow.com/questions/9464559/how-to-check-if-string-is-in-array-with-php – newbie Feb 01 '22 at 10:32

1 Answers1

2

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);
lukas.j
  • 6,453
  • 2
  • 5
  • 24
  • This is a nice solution, the problem I have is that the `$response` sometimes starts with "Ingredients:" and sometimes with something completely different. – Jake Feb 01 '22 at 10:42
  • 1
    But that is a separate thing: how to create an array from the response. – lukas.j Feb 01 '22 at 10:44
  • Thank you very much, this helped. I'm now just checking if the array() produced by `$result` is empty or not. – Jake Feb 01 '22 at 10:53
  • 1
    Note that the regex pattern is a bit "cheap". $items will only be correct if there is only one colon in the string and it is before the first comma. If not you would need to adjust the regex pattern. – lukas.j Feb 01 '22 at 10:56