Skip to content

Add Str helper to create initials #41048

Answered by erikn69
whoami15 asked this question in Ideas
Discussion options

You must be logged in to vote

Feel free to make a PR, but Str is Macroable

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

/////

Stringable::macro('initials', function(){
    $words = preg_split("/\s+/", $this);
    $initials = "";

    foreach ($words as $w) {
      $initials .= $w[0];
    }

    return new static($initials);
});
Str::macro('initials', function(string $string){
    return (string) (new Stringable($string))->initials();
});


/* TESTS */
Str::initials('Taylor Otwell');
// TO
(string) Str::of('Taylor Otwell')->initials();
// TO

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by crynobone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
3 participants