Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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('/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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...