There is certainly no shortage of this topic on the web. Unfortunately for newer developers, there is no way to tell the good advice from the bad. In this article I will show you the wrong way and the right way.
The Wrong Way
Many people out there suggest strpos()
to look for a string within a string. This is odd, though, because strpos()
is meant to find a string position. This is the wrong way to go about checking for a string in another string or variable.
If you are checking for the existence of a string and not that string’s position, using strpos()
will cause conditional checks to fail when the string you are looking for (the needle) is at the beginning of the tested content (the haystack).
If your string exists at the beginning, strpos()
will return 0
and be interpreted as boolean false. Your code will then proceed as if the string was not found, when it actually was.
$content = "solidly stated stuff"; if( strpos($content,"solid") ){ echo 'found'; } else { echo 'not found'; } // Will result in 'not found' ! |
The Right Way
Check for a string using a function that was intended to do just that: preg_match()
. If your string is found, preg_match()
will return actual true or false, allowing a conditional check to work correctly.
preg_match()
uses regular expressions, so be sure to put forward slashes inside your quotation marks. See the example below if you are unfamiliar with it.
$content = "solidly stated stuff"; if( preg_match("/solid/",$content) ){ echo 'found'; } else { echo 'not found'; } // Will find the string correctly! |
Regular expression matching is a fast and powerful way to work with strings, allowing you to do much more than look for a specific word or character.
Even though I usually prefer regexes, this is (performance-wise) bad advice.
Just use the triple equals operator, like so:
if(strpos($content, ‘solid’) !== false){
echo ‘found’;
} else {
echo ‘not found’;
}
I believe that this is even mentioned in the PHP manual..
The PHP manual mentions to watch out for “the wrong way” that I discuss at the top (when the match is at the beginning) and illustrated it with the triple operator. Regular expression algorithms are very efficient and whether or not one will be faster that the other is completely dependent on the content you search for.
Additionally, In real life you may need to look for an expression and not a static string.
Finally, the preg_match method is cleaner, more understandable code.