Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading