note 126221 added to function.array-unique
| From: | thejimy007 at gmail dot com | Date: | Tue, 06 Jul 2021 14:12:06 +0000 |
| Subject: | note 126221 added to function.array-unique | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216581@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 2a02:8108:413f:a5e0:c1d0:4e87:142b:7b65)
----
Manual Page -- https://php.net/manual/en/function.array-unique.php
Edit -- https://main.php.net/note/edit/126221
Del: integrated -- https://main.php.net/note/delete/126221/integrated
Del: useless -- https://main.php.net/note/delete/126221/useless
Del: bad code -- https://main.php.net/note/delete/126221/bad+code
Del: spam -- https://main.php.net/note/delete/126221/spam
Del: non-english -- https://main.php.net/note/delete/126221/non-english
Del: in docs -- https://main.php.net/note/delete/126221/in+docs
Del: other reasons-- https://main.php.net/note/delete/126221
Reject -- https://main.php.net/note/reject/126221
Search -- https://main.php.net/manage/user-notes.php