I have to split a user name into first name and last name, but I don't know how many elements there may be in the name. I have some working code, but it seems like it could be optimized.
Does anyone have any suggestions to make this more elegant?
function createMoodleUserNames($fullname){
$names = explode(' ',$fullname);
$prefixes = array('Dr.','Ms.','Mr.','Mrs.');
$names = explode(' ',$name);
$i = 0;
if(in_array($names[0],$prefixes)){
$firstname = $names[0].' '.$names[1];
unset($names[0]);
unset($names[1]);
}else{
$firstname = $names[0];
unset($names[0]);
}
$lastname = '';
while($i < count($names)){
$lastname .= ' '.$names[$i];
$i++;
}
$output = array();
$output[0] = $firstname;
$output[1] = $lastname;
return $output;
}
I am not sure how complex data are you parsing, but this straightforward solution might suit you:
<?php
function parseName($fullName) {
$parts = preg_split('~\s+~', $fullName);
$result = array();
if (!preg_match('~(dr|mr|ms|mrs)\.?~', strToLower($parts[0]))) {
$result[] = $parts[0];
} else {
$result[] = $parts[1];
}
$result[] = end($parts);
return $result;
}
Ignores first part if it is a recognized prefix and takes family name from the very last part.
I think line 7, $names = explode(' ',$name);
needs to be removed.
As far as optimizing, the code is pretty simple, so if it is doing what you need (ie. your test cases return results you are happy with) then the only optimization I would suggest is
$lastname = implode(' ', $names);
instead of your while loop. Since you are using unset
to remove items already processed, $names
will only be the remaining items (lastname). Though this is micro-optimizing, it will make your code a little cleaner and remove some cruft.