If you need to remove string duplication in Laravel and PHP applications, Laravel v11.20 adds a new method named deduplicate
to the String helpers, which allows you to quickly and easily remove duplicate characters.
use Illuminate\Support\{Str,Stringable}; $string = '/usr/local////path/to///desktop'; Str::deduplicate($string, '/');// "/usr/local/path/to/desktop" (new Stringable($string))->deduplicate('/')->toString();// "/usr/local/path/to/desktop"
The default replacement character in the deduplicate()
method is a space character, which could also be a use for the squish()
helper introduced in Laravel v9.7.0. Let me illustrate when squish()
might be a better choice to remove extra spaces:
Str::deduplicate(' John Smith Jr. '); // " John Smith Jr. "Str::squish(' John Smith Jr. '); // "John Smith Jr."
Note the extra space ' '
characters at the beginning and end using deduplicate()
, which is by design. Deduplicate is used to replace consecutive instances of a given character with a single character in the given string. Squish also removes other space characters, such as newlines and tabs:
// Each example returns `laravel php framework`:Str::squish(' laravel php framework '));Str::squish("laravel\t\tphp\n\nframework");Str::squish(' laravel php framework');