Remove Repeated Words in String – PHP

Usually we do remove duplicate words from a string using array functions etc, But it’s very slow doing that way because of the size of the string. 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 string.

$text =‘one one, two three, two’;
$result_text = preg_replace(“/\b(\w+)\s+\\1\b/i”, “$1″, $text);
echo “Result Text: ”.$result_text;
Result -  one, two three, two

you can see in above example there are havind two words are repeated “one” and “two”. But with the help of preg_replace function repeated words are remove.

Its a very simple and small way to Remove Repeated Words in String.

Related Posts

One thought on “Remove Repeated Words in String – PHP

Leave a Reply

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