note 104934 added to function.strrpos

From: Date: Sun, 17 Jul 2011 01:09:51 +0000
Subject: note 104934 added to function.strrpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-181594@lists.php.net to get a copy of this message
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. ---- Server IP: 72.55.140.6 Probable Submitter: 173.183.109.155 ---- Manual Page -- http://www.php.net/manual/en/function.strrpos.php Edit -- https://master.php.net/note/edit/104934 Del: integrated -- https://master.php.net/note/delete/104934/integrated Del: useless -- https://master.php.net/note/delete/104934/useless Del: bad code -- https://master.php.net/note/delete/104934/bad+code Del: spam -- https://master.php.net/note/delete/104934/spam Del: non-english -- https://master.php.net/note/delete/104934/non-english Del: in docs -- https://master.php.net/note/delete/104934/in+docs Del: other reasons-- https://master.php.net/note/delete/104934 Reject -- https://master.php.net/note/reject/104934 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181594) next »