string searching, you’re doing it wrong

First off, I’m not trying to be a complete jack-ass, just a helpful one. This article, by Stefan Ashwell, popped up on my news feed and I wanted to comment on it but can’t remember my login for the site and after 10 minutes of waiting the password reset email has yet to arrive. The non-arrival of the password process is irritating me and shows in this article title and my tone.

In the article, Stefan shows how strpos or stripos to locate a desired string or block of text.

The example he gives is as follows:

if ( stripos($sentence, 'string') ) {
   // yes it does
} else {
   // no it doesn't
} 

The problem with this example is that it will yield a false positive. This is a common mistake made by a lot of people. If we examine the php manual entry further we see, “Returns the numeric position of the first occurrence of needle in the haystack string.” The key word being numeric. This means if the string position is 0, then the expression ( stripos($sentence, 'string') ) will evaluate to false.

EDIT: Expanded explaination on why this can yield a false positive. If the string your searching for is at the beginning of the sentence, then the position returned is 0. When php reaches the statement if ( stripos($sentence, 'string') ) it interprets the return value (0) as false.

Here is a more expanded example:


$eval=(stripos('The quick brown fox jumped over the lazy dog','The'));

echo '($eval) : ';
echo ($eval) ? "pass\n" : "fail whale\n";
echo '($eval==0) : ';
echo ($eval==0) ? "pass\n" : "fail whale\n";
echo '($eval===false)';
echo ($eval===false) ? "pass\n" : "fail whale\n";
echo 'eval is '.$eval."\n";

/**
output is:

($eval) : fail whale
($eval==0) : pass
($eval===false)fail whale
eval is 0

*/

As you can see, if you want to properly search for a string using stripos or strpos, you must test for the boolean value of false ($eval===false). Alternately, you can use regex, if you’re comfortable with it. I’m of the opinion that learning some basic regex doesn’t ever hurt you.

I want to re-iterate that I wanted to leave this whole post as a comment but that doesn’t seem possible right now since that email has yet to arrive and the article requires login for commenting.

0 comments on “string searching, you’re doing it wrongAdd yours →

Leave a Reply