为了账号安全,请及时绑定邮箱和手机立即绑定

php中仅获取名字和姓氏的首字母

php中仅获取名字和姓氏的首字母

PHP
杨魅力 2023-09-15 21:23:47
我想仅使用用户名的第一个字母和姓氏的第一个字母来显示用户的姓名首字母。(测试用户=TU)即使用户输入前缀或中间名,如何才能实现此结果?(测试先生中间名用户 = TU)。这是我到目前为止的代码(但根据用户输入将显示 2 个以上的字母):public function initials() {    $words = explode(" ", $this->name );    $initials = null;    foreach ($words as $w) {        $initials .= $w[0];    }    return strtoupper($initials);}
查看完整描述

2 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

有太多变体,但这应该捕获字符串中的名字和姓氏,该字符串可能有也可能没有以句点结尾的前缀或后缀:


public function initials() {

    preg_match('/(?:\w+\. )?(\w+).*?(\w+)(?: \w+\.)?$/', $this->name, $result);

    return strtoupper($result[1][0].$result[2][0]);

}

$result[1]和$result[2]是第一个和最后一个捕获组,[0]每个捕获组的索引是字符串的第一个字符。


查看示例

这做得非常好,但是其中包含空格的名称将仅返回第二部分,例如De Jesus只会返回Jesus。您可以为姓氏添加已知的修饰符,例如de, von, van等,但祝您好运,尤其是因为它变得更长van de, van der, van den。


要扩展非英语前缀和后缀,您可能需要定义它们并将其删除,因为有些前缀和后缀可能不会以句点结尾。


$delete = ['array', 'of prefixes', 'and suffixes'];

$name = str_replace($delete, '', $this->name);


//or just beginning ^ and end $

$prefix = ['array', 'of prefixes'];

$suffix = ['array', 'of suffixes'];

$name = preg_replace("/^$prefix|$suffix$/", '', $this->name);


查看完整回答
反对 回复 2023-09-15
?
慕森王

TA贡献1777条经验 获得超3个赞

您可以使用reset()end()来实现这一点

reset() 将数组的内部指针倒回到第一个元素并返回第一个数组元素的值。

end() 将数组的内部指针前进到最后一个元素,并返回其值。

public function initials() {


 //The strtoupper() function converts a string to uppercase.

    $name  = strtoupper($this->name); 

    //prefixes that needs to be removed from the name

    $remove = ['.', 'MRS', 'MISS', 'MS', 'MASTER', 'DR', 'MR'];

    $nameWithoutPrefix=str_replace($remove," ",$name);


$words = explode(" ", $nameWithoutPrefix);


//this will give you the first word of the $words array , which is the first name

 $firtsName = reset($words); 


//this will give you the last word of the $words array , which is the last name

 $lastName  = end($words);


 echo substr($firtsName,0,1); // this will echo the first letter of your first name

 echo substr($lastName ,0,1); // this will echo the first letter of your last name


}


查看完整回答
反对 回复 2023-09-15
  • 2 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信