Reputation: 1267
I'm new to PHP. I would like to replace a string with specific duplicate words if more than three into two like below?
$wordToCheck = "abc";
$string = "abc abc abc abc Hello World abc abc abc My name is abc"
The result will be:
$outString = "abc abc Hello World abc abc My name is abc"
How can I do this in PHP?
Thanks in advance.
Upvotes: 0
Views: 819
Reputation: 32392
$string = "abc abc abc abc Hello World abc abc abc My name is abc";
print preg_replace("/abc abc abc( abc)*/","abc abc",$string);
Upvotes: 2
Reputation: 89557
You can replace more than 2 consecutive same word with the following pattern that uses a backreference to the capture group 1 (i.e. \1
):
$pattern = '~\b(\w+) \1 \K\1(?: \1)*\b ?~';
$replacement = '';
$str = preg_replace($pattern, $replacement, $str);
Note that since the \K
removes all that have been matched on the left from the match result, the two first occurences are not replaced.
Upvotes: 2
Reputation: 1502
You could use PHP's explode like this:
$wordArray = explode ( " ", $string);
$wordArray will now contain one element for each space-delimited word in the original string.
You could then say something like:
$i = 0;
while ($wordArray[$i] == $wordToCheck) {
$i++;
}
At that point, $i will tell you how many occurrences of $wordToCheck are at the beginning of the string. After that, PHP's array_shift
will remove elements from the front of the array, and, after you've shifted out enough words to leave only two, the implode
function will turn the array back into a string.
Edited to add: I have not used regular expressions; I'm not sure how to do that, and I am sure you don't need to.
Edited again: This has been tested, and will work even if the first "word" of the string is not $wordToCheck:
<?php
$wordToCheck = "abc";
$string = "abc abc abc abc Hello World abc abc abc My name is abc";
$wordArray = explode ( " ", $string);
$i = 0;
while ($wordArray[$i] == $wordToCheck) {
$i++;
}
for ($j=0; $j < $i-2; $j++) {
array_shift($wordArray);
}
$string = implode(" ",$wordArray);
echo $string;
?>
Upvotes: 0