Remove Repeated Words From String in PHP

Posted on

Usually we do remove duplicate words from a text using array functions etc, but it’s quite slow doing that way because of the size of the text. The fastest way to achieve the same result is PHP regex. You can remove duplicate words using PHP regular expressions with preg_replace. Below is a complete PHP example code using regular expression to remove duplicate words from a text using PHP.


<?php
$text ='one one, two three, two';
$result_text = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $text);
echo "Result Text: ".$result_text;
?>

Result Text:
one, two three, two

 

Leave a Reply

Your email address will not be published. Required fields are marked *