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

Php 如何比较两个可能包含额外空格、中间名或不同大小写的全名字符串中的姓氏?,php,Php,我试图创建一个函数来比较两个字符串的姓氏。这就是我到目前为止所做的,通常是有效的: public function doBillingAccountLastNameMatch( ) { if( sizeof( $this->getUserBillingAddress() ) ){ $shippingUserNames = explode( ' ', $this->getUserBillingAddress()['CustName'] );

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

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

strtolower和比较最后一个数组元素(=姓氏)已包含大小写和中间名。至于名称末尾的额外空格,只需在比较之前对其进行修剪即可。