Search code examples
phppreg-match-allimplodearray-map

Using PHP to get initials of names with 4 letters of last name


I have a small bit of code that I'm using to output the initials of a group of names:

$names = array("Tom Hanks", "Julia Roberts");
    
    $initials = implode('/', array_map(function ($name) { 
        preg_match_all('/\b\w/', $name, $matches);
        return implode('', $matches[0]);
    }, $names));
    

    echo $initials ;

This outputs TH/JR. But what I would prefer is THank/JRobe where the first 4 letters of the last name are used.

What is the best way to achieve that?


Solution

  • Just use string functions. These work for the types of names you show. These obviously won't for John Paul Jones or Juan Carlos De Jesus etc. depending on what you want for them:

    $initials = implode('/', array_map(function ($name) { 
        return $name[0] . substr(trim(strstr($name, ' ')), 0, 4);
    }, $names));
    
    • $name[0] is the first character
    • strstr return the space and everything after the space, trim the space
    • substr return the last 4 characters

    Optionally, explode on the space:

    $initials = implode('/', array_map(function ($name) { 
        $parts = explode(' ', $name);
        return $parts[0][0] . substr($parts[1], 0, 4);
    }, $names));
    

    For the preg_match:

    $initials = implode('/', array_map(function ($name) { 
        preg_match('/([^ ]) ([^ ]{4})/', $name, $matches);
        return $matches[1].$matches[2];
    }, $names));
    
    • ([^ ]) capture not a space
    • match a space
    • ([^ ]{4}) capture not a space 4 times