stringlaravel

How to extract initials from a name using 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?


Solution

  • Something like this should work:

    $names = \App\Models\User::pluck('name');
    $initials = [];
    foreach($names as $name) {
        $nameParts = explode(' ', trim($name));
        $firstName = array_shift($nameParts);
        $lastName = array_pop($nameParts);
        $initials[$name] = (
            mb_substr($firstName,0,1) .
            mb_substr($lastName,0,1)
        );
    }
    
    var_dump($initials);
    
    Output:
    array(1) {
      ["Carlos Pereira do Nascimento"]=>
      string(2) "CN"
      ["Marcos Aurelio"]=>
      string(2) "MA"
      ["Émile Durkheim"]=>
      string(2) "ÉD"
    }
    

    Note the use of mb_substr as opposed to regular substr or a string index. This will return correct values for names starting with non ASCII characters like for example "Émile"

    echo substr('Émile Durkheim', 0, 1);
    // output: b"Ã"
    echo 'Émile Durkheim'[0];
    // output: b"Ã"
    echo mb_substr('Émile Durkheim', 0, 1);
    // output: É