Jump to content

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?
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]
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.