Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

I am trying to remove the word "John" a certain number of times from a string. I read on the php manual that str_replace excepts a 4th parameter called "count". So I figured that can be used to specify how many instances of the search should be removed. But that doesn't seem to be the case since 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 just twice and leaving the other two Johns alone.

For my purposes it doesn't matter which order the replacement happens in, for example the first 2 instances can be replaced, or the last two or a combination, the order of the replacement doesn't matter.

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

like image 988
Jake Avatar asked Jan 16 '11 04:01

Jake


1 Answers

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.

like image 115
BoltClock Avatar answered Oct 10 '22 05:10

BoltClock