/**
* @param string|null $name
* @return array|null
*/
function splitName($name)
{
if (empty($name) || empty(trim($name))) {
return null;
}
//该正则是用来提取$name参数里面的中文字符的。
preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $name, $matchers);
$matchersCount = isset($matchers[0]) ? count($matchers[0]) : 0;
if ($matchersCount <= 0) {
return null;
}
$firstName = $lastName = '';
if ($matchersCount == 1) {
$lastName = mb_substr($name, 0, 1);
$firstName = mb_substr($name, 1);
} else {
foreach ($matchers[0] as $index => $value) {
if ($index == 0) {
$firstName = $value;
} else {
$lastName .= $value;
}
}
}
return compact('firstName', 'lastName');
}
var_dump(splitName("姓名"));
var_dump(splitName("姓1231名adsa"));
var_dump(splitName("买买提·吐尔逊"));
测试结果如下: