note 95677 deleted from function.strpos by danbrown

From: Date: Fri, 15 Jan 2010 16:17:06 +0000
Subject: note 95677 deleted from function.strpos by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-165008@lists.php.net to get a copy of this message
Note Submitter: jaimthorn at yahoo dot com ---- 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 ?>

« previous php.notes (#165008) next »