Search code examples
phpexplodeimplode

Get Initials From Full Names In PHP Array


I would like to take a list of names (from Wordpress) and get the initials and separate them by '/'. In most cases, there will be 2 or more names. In some cases there will be just 1 name.

For example:

John Doe
Jane Adams
Michael McDonald

should output: JD/JA/MD

Here is what I have tried so far in my attempt to figure it out.

foreach ( $result as $user )
{
   $user_id = $user->user_id1;
   $user = get_userdata( $user_id );
   $name[] = $user->display_name;
}
$comma_names =  implode('/', $name);

$words = explode("/", $comma_names);
    $initials = ""; 
    foreach ($words as $w) {
        $initials .= $w[0];
        
    }

 echo $initials;

Obviously, this only outputs the first letter of each name. Do I need to use an additional explode in my loop?

What is the best way to do this?


Solution

  • Assuming $words is an array of names (it's not 100% clear from your code), you can use preg_match_all to find the first characters in each name, then implode those values to get the initials string, and then implode all those results again to get your desired string. For example:

    $words = array(
        'John Doe',
        'Jane Adams',
        'Michael McDonald',
        'Jim'
        );
        
    $initials = implode('/', array_map(function ($name) { 
        preg_match_all('/\b\w/', $name, $matches);
        return implode('', $matches[0]);
    }, $words));
    echo $initials;
    

    Output:

    JD/JA/MM/J
    

    Demo on 3v4l.org

    If there's guaranteed to only be one space between names, you can simplify that code to just replace any character in the name string that is preceded by a word character with nothing:

    $initials = implode('/', array_map(function ($name) { 
        return preg_replace('/(?<=\w)./', '', $name);
    }, $words));
    

    The output will be the same for the sample data. Demo on 3v4l.org