Re: preg_replace() 'space' the final frontier

From: Date: Thu, 31 Jan 2002 00:53:13 +0000
Subject: Re: preg_replace() 'space' the final frontier
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-82829@lists.php.net to get a copy of this message
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

« previous php.general (#82829) next »