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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…