Here's a recursive approach using strpos() and it's offset parameter.
bvr.
<?php
function strnpos($haystack, $needle, $occurrence, $offset = 0)
{
$pos = strpos($haystack, $needle, $offset); // find next occurrence
if ($pos !== false) // needle found
{
if ($occurrence <= 1) // done
{
return $pos;
}
return strnpos($haystack, $needle, $occurrence - 1, $pos + 1); //
recurse
}
}
?>
On Thu, 31 Jan 2002 00:03:23 -0800, hugh danaher wrote:
>Mike,
>Thanks for your input on this. I'm getting better at php, but it does take
>time.
>Thanks again,
>Hugh
>
>----- Original Message -----
>From: "Mike Frazer" <[EMAIL PROTECTED]>
>To: <[EMAIL PROTECTED]>
>Sent: Wednesday, January 30, 2002 4:53 PM
>Subject: [PHP] Re: preg_replace() 'space' the final frontier
>
>
>> Okay that was quicker than I thought. Here's the code to find the nth
>> occurrance of a string within a string:
>>
>> function strnpos($string, $search, $nth) {
>> $count = 0;
>> $len = strlen($string);
>> $slen = strlen($search);
>> for ($i = 0; $i < $len; $i++) {
>> if (($i + $slen) > $len) { return FALSE; }
>> if (substr($string, $i, $slen) == $search) {
>> $count++;
>> if ($count == $nth) { return $i; }
>> }
>> }
>> if ($count != $nth) { return FALSE; }
>> }
>>
>> It returns the STARTING POINT of the nth occurrance of the string. If you
>> are looking for the first occurrance of the word "test" and "test" covers
>> positions 10-13, the function returns 10, just like the built-in functions
>> strpos() and strrpos(). $string is the string to be searched; $search is
>> what you are searcing for; $nth is the number of the occurrance you are
>> looking for.
>>
>> Hope you all can make use of this!
>>
>> Mike Frazer
>>
>>
>>
>> --
>> PHP General Mailing List (http://www.php.net/)
>> To unsubscribe, e-mail: [EMAIL PROTECTED]
>> For additional commands, e-mail: [EMAIL PROTECTED]
>> To contact the list administrators, e-mail: [EMAIL PROTECTED]
>>
>
>
>--
>PHP General Mailing List (http://www.php.net/)
>To unsubscribe, e-mail: [EMAIL PROTECTED]
>For additional commands, e-mail: [EMAIL PROTECTED]
>To contact the list administrators, e-mail: [EMAIL PROTECTED]
>
>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]