PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How to extract initials from a name using Laravel

 April 19, 2022     laravel, string     No comments   

Issue

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: É


Answered By - kaan_a
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing