如何将包含您的姓名和有时中间名的字符串转换为具有此格式的数组?
customFunction('Chris Morris');
// array('firstname' => 'Chris', 'lastname' => 'Morris')
customFunction('Chris D. Morris');
// array('firstname' => 'Chris D.', 'lastname' => 'Morris')
customFunction('Chris');
// array('firstname' => 'Chris', 'lastname' => '')
答案 0 :(得分:2)
试试这个
function splitName($name){
$name = explode(" ",$name);
$lastname= count($name)>1 ? array_pop($name):"";
return array("firstname"=>implode(" ",$name), "lastname"=>$lastname);
}
答案 1 :(得分:1)
你可以试试这个:
<?php
$arr = 'Chris D. Morris';
function customFunction($str){
$str = trim($str);
$lastSpace = strrpos($str," ");
if($lastSpace == 0){
$first = $str;
return array('firstname' => $first, 'lastname' => $last);
}else{
$first = substr($str, 0, $lastSpace);
$last = substr($str,$lastSpace);
return array('firstname' => $first, 'lastname' => $last);
}
}
$got = customFunction($arr);
print_r($got);
?>
希望它有所帮助。
答案 2 :(得分:0)
function parseName($input) {
$retval = array();
$retval['firstname'] = '';
$retval['lastname'] = '';
$words = explode(' ', $input);
if (count($words) == 1) {
$retval['firstname'] = $words[0];
} elseif (count($words) > 1) {
$retval['lastname'] = array_pop($words);
$retval['firstname'] = implode(' ', $words);
}
return $retval;
}