Test if a string contains a word in PHP?

Lucas Matos picture Lucas Matos · Feb 2, 2012 · Viewed 124k times · Source

In SQL we have NOT LIKE %string%

I need to do this in PHP.

if ($string NOT LIKE %word%) { do something }

I think that can be done with strpos()

But can’t figure out how…

I need exactly that comparission sentence in valid PHP.

if ($string NOT LIKE %word%) { do something }

Answer

Marc B picture Marc B · Feb 2, 2012
if (strpos($string, $word) === FALSE) {
   ... not found ...
}

Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.

Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.