• Czas czytania ~1 min
  • 21.04.2023

Pakiet Akronimów Str dla Laravel udostępnia makro do generowania akronimów z ciągów znaków za pomocą pomocnika Str i obsługuje klasę Stringable:Jeśli zamiast tego chcesz użyć makra bezpośrednio, oto jak to wygląda w całości w momencie pisania:

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

O

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...

O autorze CrazyBoy49z
WORK EXPERIENCE
Kontakt
Ukraine, Lutsk
+380979856297