Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract initials from a name using Laravel

Tags:

string

laravel

I have the method below that returns me a list of registered users:

$users = \App\Models\User::all();

It turns out that I would like to present only the initials of the names on that list.

Example:

Carlos Pereira do Nascimento = CN

Marcos Aurelio = MA

Sandra Lopes = SL

How could I do this by getting this data from the list?

Is it possible for me to treat this list by taking only the initials of the variable $ name?

like image 944
AmandaRJ Avatar asked Oct 26 '25 02:10

AmandaRJ


2 Answers

For anyone looking for a simple, one-line, framework-agnostic solution:

$initials = preg_filter('/[^A-Z]/', '', $str);
like image 174
Dankim Avatar answered Oct 28 '25 23:10

Dankim


You can use Laravel's accessor to get the initials modifying the following code:

public function getInitialsAttribute(){
    $name = 'Carlos Pereira do Nascimento';
    $name_array = explode(' ',trim($name));

    $firstWord = $name_array[0];
    $lastWord = $name_array[count($name_array)-1];

    return $firstWord[0]."".$lastWord[0];
}

Now, you can get the initals using {{ $user->initials }}

like image 23
Shrey Avatar answered Oct 29 '25 00:10

Shrey