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

我想仅使用用户名的第一个字母和姓氏的第一个字母来显示用户的姓名首字母。(测试用户=TU)


即使用户输入前缀或中间名,如何才能实现此结果?(测试先生中间名用户 = TU)。


这是我到目前为止的代码(但根据用户输入将显示 2 个以上的字母):


public function initials() {

    $words = explode(" ", $this->name );

    $initials = null;

    foreach ($words as $w) {

        $initials .= $w[0];

    }

    return strtoupper($initials);

}


杨魅力
浏览 103回答 2
2回答

繁华开满天机

有太多变体,但这应该捕获字符串中的名字和姓氏,该字符串可能有也可能没有以句点结尾的前缀或后缀: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);

慕森王

您可以使用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}
打开App,查看更多内容
随时随地看视频慕课网APP