0

I would like to do some simple replacement using php.

For the first occurrence of "xampp" , replace it as "xp".

For the second / last occurrence of "xampp", replace it as "rrrr"

    $test = "http://localhost/xampp/splash/xampp/.php";

echo $test."<br>";
$count = 0;
$test = str_replace ("xampp","xp",$test,$count);

echo $test."<br>";

$count = 1;
$test = str_replace ("xampp","rrrr",$test,$count);
echo $test;

After looking the doc, I found that $count is to return the place where the string matchs only. It do not replace the string by specific occurrence assigned. So are there any ways to do the task?

tchrist
  • 78,834
  • 30
  • 123
  • 180
user782104
  • 13,233
  • 55
  • 172
  • 312

1 Answers1

1

You could do it with preg_replace_callback, but strpos should be more efficient if the replacements aren't necessarily sequential.

function replaceOccurrence($subject, $find, $replace, $index) {
    $index = 0;

    for($i = 0; $i <= $index; $i++) {
        $index = strpos($subject, $find, $index);

        if($index === false) {
            return $subject;
        }
    }

    return substr($subject, 0, $index) . $replace . substr($subject, $index + strlen($find));
}

Here's a demo.

Ry-
  • 218,210
  • 55
  • 464
  • 476