Re: Split haystack at nth occurrence of needle?
| From: | Robert Cummings | Date: | Wed, 22 Sep 2004 16:58:25 +0000 |
| Subject: | Re: Split haystack at nth occurrence of needle? | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-197588@lists.php.net to get a copy of this message | ||
On Wed, 2004-09-22 at 12:31, Brian Dunning wrote:
> > <?
> > $string = 'one<br>two<br>three<br>four<br>five';
> > $nthPos = 4;
> > $tmpArr = explode( '<br>', $string );
> > $nthString = $tmpArr[($nthPos - 1)];
> > ?>
>
> Thanks Chris, that works great, but it's not doing what I want. I'm
> just trying to get the position of the 3rd occurrence (for example) of
> '<br>'. So I'm looking for a function that will return the value 19,
> given the above example string.
The following should get you going:
function strpos_nth( $hay, $needle, $n=1 )
{
$offset = -1;
if( $n < 1 )
{
return false;
}
while( $n-- > 0 )
{
if( ($offset = strpos( $hay, $needle, $offset + 1 )) === false )
{
return false;
}
}
return $offset;
}
Cheers,
Rob.
--
.------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com
|
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting |
| a powerful, scalable system for accessing system services |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for |
| creating re-usable components quickly and easily. |
`------------------------------------------------------------'