Add string helper to get initials from a string#59230
Add string helper to get initials from a string#59230taylorotwell merged 5 commits intolaravel:12.xfrom
Conversation
…optionally returning them in uppercase.
| $parts = mb_split("\s+", $value); | ||
|
|
||
| $parts = array_map(fn ($part) => mb_substr($part, 0, 1), $parts); | ||
|
|
||
| $initials = implode('', $parts); |
There was a problem hiding this comment.
Technically, you could simplify this to just
| $parts = mb_split("\s+", $value); | |
| $parts = array_map(fn ($part) => mb_substr($part, 0, 1), $parts); | |
| $initials = implode('', $parts); | |
| $initials = trim(preg_replace('/\b([[:alpha:]]).*?\b(?:\s+)?/', '$1', $value)); |
There was a problem hiding this comment.
Hmm. I agree you can probably try and go down that route, but I followed the current style of the other helpers in the class. And to me personally, the intent of what my three lines do is much more clearer to a developer than having to see what yours does. (clever is not always clearer)
Also - your version isn't multibyte safe. Running that using the string "über eats'" would return übe" whereas mine returns "üe" as per expectation.
There was a problem hiding this comment.
I didn't try to be clever, I just wanted to avoid unnecessary split/implode + mapping when you just want to extract something and do not care about the rest.
Sure, the suggestion can be improved like with mb_ereg() and or replacing [[:alpha:]] with something more suiting.
There was a problem hiding this comment.
I didn't say you were trying to be clever - at least that's not what I intended. I just prefer - in general - code that is immediately clear to the developer/reader of the code. It's just personal flavour/taste. No worries.
I'm just going to leave the PR as is and see whether it gets merged - feel free to suggest changes though
* Add documentation for the new string helper initials introduced in PR laravel/framework#59230 * update docs --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
This PR introduces the support for retrieving the initials from a string, optionally capitalizing the string:
It also introduces fluent API support: