note 104934 deleted from function.strrpos by danbrown

From: Date: Mon, 18 Jul 2011 14:27:32 +0000
Subject: note 104934 deleted from function.strrpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181656@lists.php.net to get a copy of this message
Note Submitter: Kevin S ---- Careful! Protozoid's instr example will not work if your needle exists (and only exists) at the start of the string. For example: <?php $var = "bowchickawowwow"; if (instr($var, "bow")) // returns false (even though it exists) print "needle found in the haystack!"; function instr($haystack, $needle) { $pos = strpos($haystack, $needle, 0); if ($pos != 0) return true; return false; } ?> This is because the needle exists at string offset 0, not 1. To check if it does not exist in the string, compare with === (As is indicated by the massive red warning box in the documentation for strpos.) A better function would be this: <?php function instr($haystack, $needle) { return strpos($haystack, $needle) !== FALSE; } ?> This returns the correct result, and has the added benefit of being only one line of code.

« previous php.notes (#181656) next »