• Время чтения ~1 мин
  • 21.04.2023

Пакет 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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Об авторе CrazyBoy49z
WORK EXPERIENCE
Контакты
Ukraine, Lutsk
+380979856297