Generate String Acronyms with this Laravel Macro

Packages

April 21st, 2023

Generate String Acronyms with this Laravel Macro

The Str Acronym package for Laravel provides a macro for generating acronyms from strings using the Str helper and supports the Stringable class:

use Illuminate\Support\Str;
 
Str::acronym('Laravel News'); // LN
Str::acronym('Amazon Web Services'); // AWS

If you prefer using Stringable, you can use this macro as follows:

Str::of('Laravel News')->headline()->acronym(); // LN

Lastly, it also supports a delimiter character you can use between each letter in the acronym:

Str::acronym('Eric Barnes', '.'); // E.B.
Str::acronym('Eric L. Barnes', '.'); // E.L.B.

This tiny macro could help generate text-based chat avatars for users based on first and last names, for example.

If you instead want to use the macro directly, here's what it looks like in full at the time of writing:

Str::macro('acronym', function ($string, $delimiter = '') {
if (empty($string)) {
return '';
}
 
$acronym = '';
foreach (preg_split('/[^\p{L}]+/u', $string) as $word) {
if(!empty($word)){
$first_letter = mb_substr($word, 0, 1);
$acronym .= $first_letter . $delimiter;
}
}
 
return $acronym;
});
 
Stringable::macro('acronym', function (string $delimiter = '') {
return new Stringable (Str::acronym($this->value, $delimiter));
});

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.