Tag Archive for 'boundaries'

PHP: search for full words only

I needed to search for full words in strings. strpos() would match parts of a word. Ex. I want to match the word “ass,” but not “assistant.”

Regular expressions to the rescue:

preg_match("/\b$needle\b/", $haystack);

“\b” stands for word boundary. Take care to use the lowercase “\b”, not “\B”, which is the negated version that matches everywhere that “\b” does not.

If you liked this post, please subscribe to my feed. Thanks for visiting!