How to use str_replace() to remove text a certain number of times only in PHP?

As Artelius explains, the last parameter to str_replace() is set by the function. There's no parameter that allows you to limit the number of replacements.

Only preg_replace() features such a parameter:

echo preg_replace('/John/', 'dude', $string, $numberOfInstances);

That is as simple as it gets, and I suggest using it because its performance hit is way too tiny compared to the tedium of the following non-regex solution:

$len = strlen('John');

while ($numberOfInstances-- > 0 && ($pos = strpos($string, 'John')) !== false)
    $string = substr_replace($string, 'dude', $pos, $len);

echo $string;

You can choose either solution though, both work as you intend.


You've misunderstood the wording of the manual.

If passed, this will be set to the number of replacements performed.

The parameter is passed by reference and its value is changed by the function to indicate how many times the string was found and replaced. Its initial value is discarded.

Tags:

Php

String