第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

php中僅獲取名字和姓氏的首字母

php中僅獲取名字和姓氏的首字母

PHP
楊魅力 2023-09-15 21:23:47
我想僅使用用戶名的第一個(gè)字母和姓氏的第一個(gè)字母來顯示用戶的姓名首字母。(測(cè)試用戶=TU)即使用戶輸入前綴或中間名,如何才能實(shí)現(xiàn)此結(jié)果?(測(cè)試先生中間名用戶 = TU)。這是我到目前為止的代碼(但根據(jù)用戶輸入將顯示 2 個(gè)以上的字母):public function initials() {    $words = explode(" ", $this->name );    $initials = null;    foreach ($words as $w) {        $initials .= $w[0];    }    return strtoupper($initials);}
查看完整描述

2 回答

?
繁華開滿天機(jī)

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊

有太多變體,但這應(yīng)該捕獲字符串中的名字和姓氏,該字符串可能有也可能沒有以句點(diǎn)結(jié)尾的前綴或后綴:


public function initials() {

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

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

}

$result[1]和$result[2]是第一個(gè)和最后一個(gè)捕獲組,[0]每個(gè)捕獲組的索引是字符串的第一個(gè)字符。


查看示例

這做得非常好,但是其中包含空格的名稱將僅返回第二部分,例如De Jesus只會(huì)返回Jesus。您可以為姓氏添加已知的修飾符,例如de, von, van等,但祝您好運(yùn),尤其是因?yàn)樗兊酶L(zhǎng)van de, van der, van den。


要擴(kuò)展非英語前綴和后綴,您可能需要定義它們并將其刪除,因?yàn)橛行┣熬Y和后綴可能不會(huì)以句點(diǎn)結(jié)尾。


$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);


查看完整回答
反對(duì) 回復(fù) 2023-09-15
?
慕森王

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊

您可以使用reset()end()來實(shí)現(xiàn)這一點(diǎn)

reset() 將數(shù)組的內(nèi)部指針倒回到第一個(gè)元素并返回第一個(gè)數(shù)組元素的值。

end() 將數(shù)組的內(nèi)部指針前進(jìn)到最后一個(gè)元素,并返回其值。

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


}


查看完整回答
反對(duì) 回復(fù) 2023-09-15
  • 2 回答
  • 0 關(guān)注
  • 194 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)