Reputation: 906
How can you convert a string that contains your first and last name and sometimes middle name into an array with this format?
customFunction('Chris Morris');
// array('firstname' => 'Chris', 'lastname' => 'Morris')
customFunction('Chris D. Morris');
// array('firstname' => 'Chris D.', 'lastname' => 'Morris')
customFunction('Chris');
// array('firstname' => 'Chris', 'lastname' => '')
Upvotes: 0
Views: 82
Reputation: 11859
you can try this:
<?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);
?>
hope it helps.
Upvotes: 1
Reputation: 1269
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;
}
Upvotes: 0
Reputation: 723
Try this
function splitName($name){
$name = explode(" ",$name);
$lastname= count($name)>1 ? array_pop($name):"";
return array("firstname"=>implode(" ",$name), "lastname"=>$lastname);
}
Upvotes: 2