2 回答

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

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
}
- 2 回答
- 0 關(guān)注
- 194 瀏覽
添加回答
舉報(bào)