note 126221 deleted from function.array-unique by crell

From: Date: Tue, 12 Apr 2022 00:52:46 +0000
Subject: note 126221 deleted from function.array-unique by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218168@lists.php.net to get a copy of this message
Note Submitter: thejimy007 at gmail dot com ---- If you're looking for the fastest way to remove duplicate words in a string, because you may do so in the millions (because it doesn't matter if you do only some thousands) and use this code: $result = implode(" ", array_unique( explode(" ", $string) )); Then there is currently (2021) with the most recent PHP 7/8 versions only one faster alternative: $result = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $string); will remove all consecutive duplicate words and it's the fastest of all, taking only 30-40% of the time. $result = preg_replace("/\b(\w+)\s+.*\\1\b/i", "$1", $string); will remove all duplicate words anywhere in the string, requiring about 80%-85% of the time. Of course, all speeds may vary depending on the length of your strings and their content. Please test for your case.

« previous php.notes (#218168) next »