note 96576 deleted from function.strpos by danbrown
| From: | danbrown@php.net | Date: | Tue, 17 May 2011 16:48:56 +0000 |
| Subject: | note 96576 deleted from function.strpos by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179819@lists.php.net to get a copy of this message | ||
Note Submitter: jaimthorn at yahoo dot com
----
restaurant.nl may find it bizarre, but I prefer this implementation of strnpos because it
doesn't give visible warnings when supplied with a needle of length 0 (which is, admittedly,
non-standard behavior), AND it's faster...
<?php
/**
* Returns the position of the $nth occurrence of $needle in $haystack, or false if it doesn't
exist, or false when illegal parameters have been supplied.
*
* @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 looking for $needle.
* @return MIXED integer either the position of the $nth occurrence of $needle in $haystack,
* or boolean false if it can't be found.
*/
function strnpos( $haystack, $needle, $nth, $offset = 0 )
{
if( 1 > $nth || 0 === strlen( $needle ) )
{
return false;
}
// $offset is incremented in the call to strpos, so make sure that the first call starts at the
right position by initially decrementing $offset.
--$offset;
do
{
$offset = strpos( $haystack, $needle, ++ $offset );
} while( --$nth && false !== $offset );
return $offset;
}
?>