For a lot of projects, we use initials (Lasse Rafn = LR or LRA) to display employees and users. Repeating code over and over eventually felt wrong, so I packed the primary functionality into two different packages.
Prepare yourself for some shameless self-promotion... okay, I do feel a bit shame.
The core package turns names into initials from the desired length. It should handle all names you throw at it (otherwise, let me know and I'll have fix out shortly)
So, for example, if your user is named "Jannie Doe", and want only two letters (default) it will return the first letter of the first name, and the first letter of the last name, returning JD.
For names such as "John Marshal Ike", it will use the same logic as above and grab the first letter of each name, with the desired length.
If the name is "John" without any last name, but you still want 2 letters returned, it will grab the first two letters, returning JO.
If you want 3 letters and the name only consists of two names (John Doe), it will grab the first letter of the first name, and the first two letters of the last name, hence returning JDO.
I think you get it. Basically, it accepts a name and spits out initials.
<?php use LasseRafn\Initials\Initials; echo (new Initials('Lasse Rafn'))->generate(); // Output: LR
Now, let's step it up a bit. What if you would like one of those cool avatars you'll see everywhere? This package is for you. It renders an actual image containing the generated initials. You can customize it almost entirely to your needs with a simple API. The example below will use almost all options available, but you can leave anything but the name and still get an image back. Example:
<?php $avatar = new LasseRafn\InitialAvatarGenerator\InitialAvatar(); return $avatar->name('Lasse Rafn') ->length(2) ->fontSize(0.5) ->size(96) // 48 * 2 ->background('#8BC34A') ->color('#fff') ->cache() ->generate() ->stream('png', 100);
This package uses the core package above, to yield the exact same initials.
You can also use my api service, for free: https://ui-avatars.com.