debugphplaravelMinor
My PHP function that reads names and attempts to fix the suffixes
Viewed 0 times
fixthephpfunctionnamessuffixesreadsthatattemptsand
Problem
I am reading a text file that has some name inconsistencies. For example I have names like:
As you can see I can split the name by first name and last name however the suffixes are placed incorrectly. Ideally the names should be:
That being said this is what I have but I feel Im over complicating something simple. Any tips? Also my logic does not account for the suffix of V since that could be a middle initial also.
MILLERS, WALTER M IV
DUPONTE, THOMAS B. II
HARDIWAY, GRANT U. SR.
GUIDRY, PAUL JOHNAs you can see I can split the name by first name and last name however the suffixes are placed incorrectly. Ideally the names should be:
WALTER M MILLERS IV
THOMAS B. DUPONTE II
GRANT U. HARDIWAY SR.
PAUL JHN GUIDRYThat being said this is what I have but I feel Im over complicating something simple. Any tips? Also my logic does not account for the suffix of V since that could be a middle initial also.
private function extractFullName($name){
$suffix = collect(['II', 'III', 'IV', 'JR.', 'SR.']);
// lets first assemble a full name from the row
$fullNameArray = explode(",", $name);
$firstName=trim($fullNameArray[1]);
$lastName=trim($fullNameArray[0]);
//lets look at the FIRST NAME for II/III/IV/JR./SR.
$suffix->each(function ($item, $key) use ($firstName, $lastName) {
if (strpos($firstName, " ".$item)){
$firstName = preg_replace('/ '.$item.'$/', '', $firstName);
$lastName.=' '.$item;
return false;
}
});
//Basically arranging it in a 'firstname lastname II/III/IV/JR./SR.' format
$name = $firstName." ".$lastName;
$name = ucwords(strtolower($name));
return $name;
}Solution
You could simplify you code quite a bit by utilising collections more:
private function extractFullName($name)
{
$suffix = collect(['II', 'III', 'IV', 'JR.', 'SR.'])->first(function ($suffix) use ($name) {
return ends_with($name, $suffix);
});
$name = $suffix ? rtrim($name, $suffix) : $name;
return collect(explode(',', $name))->map(function ($name) {
return trim(ucwords(strtolower($name)));
})->reverse()->implode(' ') . ' ' . $suffix;
}Code Snippets
private function extractFullName($name)
{
$suffix = collect(['II', 'III', 'IV', 'JR.', 'SR.'])->first(function ($suffix) use ($name) {
return ends_with($name, $suffix);
});
$name = $suffix ? rtrim($name, $suffix) : $name;
return collect(explode(',', $name))->map(function ($name) {
return trim(ucwords(strtolower($name)));
})->reverse()->implode(' ') . ' ' . $suffix;
}Context
StackExchange Code Review Q#159921, answer score: 3
Revisions (0)
No revisions yet.