Пакет Str Acronym для Laravel предоставляет макрос для генерации аббревиатур из строк с помощью вспомогательного модуля Str и поддерживает класс Stringable:Если вместо этого вы хотите использовать макрос напрямую, вот как он выглядит полностью на момент написания:
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.
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.