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

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
}
- 2 回答
- 0 關注
- 197 瀏覽
添加回答
舉報