note 95677 added to function.strpos

From: Date: Fri, 15 Jan 2010 12:29:07 +0000
Subject: note 95677 added to function.strpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-164999@lists.php.net to get a copy of this message
pawhox, below, posted a function strnpos. This is an improved (faster) version of that function. <?php /** * Returns the position of the $nth occurrence of $needle in $haystack, or false if it can't be found. * * @param string $haystack the string to search in. * @param string $needle the string to search for. * @param integer $nth the number of the occurrence to look for. * @param integer $offset the position in $haystack to start looknig for $needle. * @return MIXED the position of the $nth occurrence of $needle in $haystack, * or false if it can't be found. */ function strnpos( $haystack, $needle, $nth, $offset = 0 ) { // The substr_count call that follows is only a speed optimization. Without it, this function will be // - a bit slower if the $nth occurrence of $needle doesn't exist in $haystack; // - marginally faster if the $nth occurrence of $needle does exist in $haystack; // but it will continue to work properly. if( 1 > $nth || 0 > $offset || 0 === strlen( $needle ) || substr_count( $haystack, $needle ) < $nth ) { return false; } // We're incrementing $offset in the call to strpos (to prevent it from getting stuck in the loop); // so we make sure that the first call starts at the right position by initially decrementing $offset. --$offset; do { $offset = strpos( $haystack, $needle, ++ $offset ); } while( --$nth && $offset !== false ); return $offset; } /** * Case-insensitive version of strnpos. * * @see function strnpos */ function strnipos( $haystack, $needle, $nth, $offset = 0 ) { return strnpos( strtolower( $haystack ), strtolower( $needle ), $nth, $offset ); } echo strnpos("I like the bananas. You like coke. We like chocolate.", "like", 2); // output: 24 ?> ---- Server IP: 69.147.83.197 Probable Submitter: 77.249.171.118 ---- Manual Page -- http://www.php.net/manual/en/function.strpos.php Edit -- https://master.php.net/note/edit/95677 Del: integrated -- https://master.php.net/note/delete/95677/integrated Del: useless -- https://master.php.net/note/delete/95677/useless Del: bad code -- https://master.php.net/note/delete/95677/bad+code Del: spam -- https://master.php.net/note/delete/95677/spam Del: non-english -- https://master.php.net/note/delete/95677/non-english Del: in docs -- https://master.php.net/note/delete/95677/in+docs Del: other reasons-- https://master.php.net/note/delete/95677 Reject -- https://master.php.net/note/reject/95677 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#164999) next »