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

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -