Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...