strnpos() (was: Re: preg_replace() 'space' the final frontier)

From: Date: Thu, 31 Jan 2002 09:59:22 +0000
Subject: strnpos() (was: Re: preg_replace() 'space' the final frontier)
Groups: php.general 
Request: Send a blank email to php-general+get-82897@lists.php.net to get a copy of this message
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" <mike@invertedmind.com> >To: <php-general@lists.php.net> >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: php-general-unsubscribe@lists.php.net >> For additional commands, e-mail: php-general-help@lists.php.net >> To contact the list administrators, e-mail: php-list-admin@lists.php.net >> > > >-- >PHP General Mailing List (http://www.php.net/) >To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net >For additional commands, e-mail: php-general-help@lists.php.net >To contact the list administrators, e-mail: php-list-admin@lists.php.net > >

« previous php.general (#82897) next »