是否有更简单的方法来修复名称中的后缀?

时间:2017-04-05 14:49:40

标签: php laravel

我正在阅读一个名称不一致的文本文件。例如,我的名字如下:

MILLER, WALTER MCNAB IV
DUPONT, THOMAS B. II
HARDEWAY, GRANT U. SR.

如您所见,我可以按名字和姓氏拆分名称,但后缀不正确。理想情况下,名称应为:

WALTER MCNAB MILLER IV
THOMAS B. DUPONT II
GRANT U. HARDEWAY SR.

据说这就是我所拥有的,但我觉得我过于简单化了。有什么提示吗?

private function extractFullName($name){


//I cant do V since V could be someone's middle initial also :(
        $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 = $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($lawyerName));
        return $name;
    }

2 个答案:

答案 0 :(得分:1)

示例总是那样:

$arr = explode(" ", $name); $a=array_pop($arr); $b=trim(array_shift($arr),','); array_push($arr,$b); array_push($arr,$a); print implode(' ',$arr); ??

然后你可以做

{{1}}

阅读@ CD001评论: - )

答案 1 :(得分:1)

您当时的逻辑不应该有效,因为您没有通过引用传递$firstname$lastname

据说这可以简化你的代码:

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;
}

希望这有帮助!