Check if string contains all values in array with php -



Check if string contains all values in array with php -

what have far:

$searchquery = "keyword1 keyword2"; $searcharray = explode(" ", $searchquery); $stringtocheck = "keyword1 keyword3 keyword2"; foreach ($searcharray $searchkeyword) { if (strpos($stringtocheck, $searchkeyword) !== false) : //do endif; } endif;

what want display if values in search query found in string. current code above, if string contains keyword1 , keyword2, "does something" twice, 1 time each match. comes true if string contains keyword1 not keyword2, in case displays content once.

solution function str_contains_all($haystack, array $needles) { foreach ($needles $needle) { if (strpos($haystack, $needle) === false) { homecoming false; } } homecoming true; }

usage:

$haystack = 'foo, bar, baz'; $needles = array('foo', 'bar', 'baz'); if (str_contains_all($haystack, $needles)) { echo "success\n"; // ... } notes

since specified only wish perform action when "haystack" string contains all substring "needles", safe homecoming false find needle not in haystack.

other

using if (...): /* ... */ endif; uncommon in php experience. think developers prefer c-style if (...) { /* ... */ } syntax.

php arrays string

Comments

Popular posts from this blog

Using Android Volley to post an array to PHP -

python - How to add an model instance to a django queryset? -

angularjs - No 'Access-Control-Allow-Origin' error from local domain to public API -