Remove Duplicate Characters in Strings With Laravel

  • Published on 19 August, 2024
  • Words: 179

The Laravel team released v11.20 this week, including a new collection method, a deduplicate string method, the ability to use Enums with AssertableJson, and more.

Remove Duplicate Characters in Strings With Laravel

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
');

 

Antonio Jenaro

Antonio Jenaro

Web Developer

Source: Laravel news

Start the conversation

Become a member of Antonio Jenaro to start commenting.

Sign up now

Already a member? Sign in