Jump to content

Archived

This topic is now archived and is closed to further replies.

dagnasty

Replacing third string occurance within a larger string

Recommended Posts

I need to be enlightened of a function or a way to replace the third occurance of a string within a larger string.

For example, if I wanted to replace the third occurance of "cat" within each string,

For example

1st string: dog cat bird owl cat bird cat elephant
2st string bird cat dog cat cat dog elephant

what would I do?

Share this post


Link to post
Share on other sites
One way

[code]
<?php
function replaceNth ($s, $r, $str, $n) {
// args : search, replace, string, N
    $l = strlen($s);
    $pos = 0;
    for ($i=0; $i<$n; $i++) {
    if (($pos = strpos($str,$s,$pos))===false) {
        return $str;
    }
    $pos += $l;
    }
    return substr_replace($str, $r, $pos-$l, $l);
}

// Test it

$search = 'cat';
$replace = 'tiger';

$str = array('dog cat bird owl cat bird cat elephant',
'bird cat dog cat cat dog cat elephant',
'bird cat dog cat dog elephant',
'bird cat dog cat dog cat');

foreach ($str as $x) echo $x, '<br>', replaceNth($search, $replace, $x, 3),'<br><br>';
?>[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.