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

I am trying to remove the word "John" a certain number of times from a string. I read in the php manual that str_replace excludes the 4th parameter called "count". So I decided what could be used to indicate how many search instances to remove. But this is not like the following:

$string = 'Hello John, how are you John. John are you happy with your life John?';

$numberOfInstances = 2;

echo str_replace('John', 'dude', $string, $numberOfInstances);

replaces all instances of the word "John" with "dude" instead of doing it only twice and leaving the other two Jones alone.

For my purposes, it does not matter in which order the replacement occurs, for example, the first 2 copies can be replaced, or the last two or a combination, the replacement order does not matter.

So, is there a way to use str_replace () this way or is there another built-in function (non-regex) that can achieve what I'm looking for?

+3
source share
5 answers

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

Only preg_replace()has such a parameter:

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

It's as simple as it gets, and I suggest using it because its performance rating is too low compared to the boredom of the following non-repressive solution:

$len = strlen('John');

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

echo $string;

You can choose any solution, although both work the way you plan.

+3
source

You misunderstood the wording of the manual.

, .

, , . .

+5

, , php, .

- strripos substr .

, , preg_replace_callback , .

, , , " ". , .

+1

, , , :

function str_replace_occurrences($find,$replace,$string,$count = 0)
{
    if($count == 0)
    {
        return str_replace($find,$replace,$string);
    }

    $pos = 0;
    $len = strlen($find);
    while($pos < $count && false !== ($pos = strpos($string,$find,$pos)))
    {
        $string = substr_replace($string,$replace,$pos,$len);
    }

    return $string;
}

, .

0
function str_replace_occurrences($find, $replace, $string, $count = -1) {
    // current occrurence 
    $current = 0;
    // while any occurrence 
    while (($pos = strpos($string, $find)) != false) {
        // update length of str (size of string is changing)
        $len = strlen($find);
        // found next one 
        $current++;
        // check if we've reached our target 
        // -1 is used to replace all occurrence 
        if($current <= $count || $count == -1) {
            // do replacement 
            $string = substr_replace($string, $replace, $pos, $len);
        } else {
            // we've reached our 
            break;
        }
    }
    return $string;
}
0
source

Source: https://habr.com/ru/post/1785685/


All Articles