Tag Archive for 'strpos'

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!

PHP: speed of string comparison functions

Here is a recent benchmark of various PHP string comparison functions. Not surprisingly, the fastest is strpos. But did you know that preg_match is faster than strstr and not much slower than strpos? This contradicts the following note in the official PHP manual:

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

ereg is by far the slowest.

So, the best function to use to do a simple check to see if a string contains a particular substring is strpos. In all other cases preg_match might be superior to strstr. YMMV.