亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 197 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號