如何比较两个全名字符串中的姓氏,其中可能包含额外的空格、中间名或不同的大小写



我正在尝试创建一个比较两个字符串的姓氏的函数。这就是我到目前为止所拥有的,它通常有效:

public function doBillingAccountLastNameMatch(  ) {
    if( sizeof( $this->getUserBillingAddress() ) ){
        $shippingUserNames  = explode( ' ', $this->getUserBillingAddress()['CustName'] );
        $userNames          = explode( ' ', $this->getUserData()['UName']  );
        if( strtolower( $shippingUserNames[ sizeof( $shippingUserNames ) - 1 ] ) == strtolower( $userNames[ sizeof( $userNames ) - 1 ] ) ){
            return CustomHelper::functionSuccessResponse();
        }else{
            return CustomHelper::functionErrorResponse( 'User Payment Data is not found' );
        }
    }else{
        return CustomHelper::functionErrorResponse( 'User Payment Data is not found' );
    }
}
但是,在某些情况下,两个名称中的一个有一个额外的空格(即"John Doe"与"John Doe"),或者可能有一个中间名(即"John James Doe"与"John Doe"

),或者可能有不同的大写(即"john doe"与"John Doe")。

涵盖所有这些方案的简单而优雅的方法是什么?

如果不是爆炸,而是trim()输入,然后从最后一个空格中提取字符串(使用 strrpos() 查找最后一次出现并提取substr())。 然后使用不区分大小写的比较(strcasecmp() 如果字符串匹配,则返回 0)比较两个字符串...

$sName = trim($this->getUserBillingAddress()['CustName']);
$cName = trim($this->getUserData()['UName']);
$shippingUserName  = substr($sName, strrpos( $sName , ' ' )+1);
$userName          = substr($cName, strrpos( $cName , ' ' )+1);
if( strcasecmp( $shippingUserName, $userName ) === 0 ){
    return CustomHelper::functionSuccessResponse();
}
else    {
    return CustomHelper::functionErrorResponse( 'User Payment Data is not found' );
}

最新更新