• Час читання ~1 хв
  • 21.04.2023

Пакет Str Acronym для Laravel надає макрос для генерації акронімів з рядків за допомогою Str helper і підтримує клас 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