Skip to content

Commit fc4cef4

Browse files
[12.x] Add ability to deduplicate multiple characters with a single Str::deduplicate call (#56548)
* Add ability to deduplicate multiple characters with a single call * Updating to use array_reduce * Update method docblock * Update Str.php --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent c9af3bc commit fc4cef4

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/Illuminate/Support/Str.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -371,12 +371,20 @@ public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?st
371371
* Replace consecutive instances of a given character with a single character in the given string.
372372
*
373373
* @param string $string
374-
* @param string $character
374+
* @param array<string>|string $characters
375375
* @return string
376376
*/
377-
public static function deduplicate(string $string, string $character = ' ')
377+
public static function deduplicate(string $string, array|string $characters = ' ')
378378
{
379-
return preg_replace('/'.preg_quote($character, '/').'+/u', $character, $string);
379+
if (is_string($characters)) {
380+
return preg_replace('/'.preg_quote($characters, '/').'+/u', $characters, $string);
381+
}
382+
383+
return array_reduce(
384+
$characters,
385+
fn ($carry, $character) => preg_replace('/'.preg_quote($character, '/').'+/u', $character, $carry),
386+
$string
387+
);
380388
}
381389

382390
/**

tests/Support/SupportStrTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,7 @@ public function testDedup()
482482
$this->assertSame('what', Str::deduplicate('whaaat', 'a'));
483483
$this->assertSame('/some/odd/path/', Str::deduplicate('/some//odd//path/', '/'));
484484
$this->assertSame('ムだム', Str::deduplicate('ムだだム', ''));
485+
$this->assertSame(' laravel forever ', Str::deduplicate(' laravell foreverrr ', [' ', 'l', 'r']));
485486
}
486487

487488
public function testParseCallback()

0 commit comments

Comments
 (0)