之前有分享了用javascript在客戶端進行姓名拆分的方法,後應項目需要,又用PHP實現了,貼出來 跟大家分享交流:
/** * 把全名拆分為姓氏和名字 * @param string $fullname 全名 * @return array 一維數組,元素一是姓,元素二為名 * @author: 風柏楊<[email protected]> */ function splitName($fullname){ $hyphenated = array('歐陽','太史','端木','上官','司馬','東方','獨孤','南宮','萬俟','聞人','夏侯','諸葛','尉遲','公羊','赫連','澹台','皇甫', '宗政','濮陽','公冶','太叔','申屠','公孫','慕容','仲孫','鐘離','長孫','宇文','城池','司徒','鮮於','司空','汝嫣','闾丘','子車','亓官', '司寇','巫馬','公西','颛孫','壤驷','公良','漆雕','樂正','宰父','谷梁','拓跋','夾谷','軒轅','令狐','段干','百裡','呼延','東郭','南門', '羊舌','微生','公戶','公玉','公儀','梁丘','公仲','公上','公門','公山','公堅','左丘','公伯','西門','公祖','第五','公乘','貫丘','公皙', '南榮','東裡','東宮','仲長','子書','子桑','即墨','達奚','褚師'); $vLength = mb_strlen($fullname, 'utf-8'); $lastname = ''; $firstname = '';//前為姓,後為名 if($vLength > 2){ $preTwoWords = mb_substr($fullname, 0, 2, 'utf-8');//取命名的前兩個字,看是否在復姓庫中 if(in_array($preTwoWords, $hyphenated)){ $lastname = $preTwoWords; $firstname = mb_substr($fullname, 2, 10, 'utf-8'); }else{ $lastname = mb_substr($fullname, 0, 1, 'utf-8'); $firstname = mb_substr($fullname, 1, 10, 'utf-8'); } }else if($vLength == 2){//全名只有兩個字時,以前一個為姓,後一下為名 $lastname = mb_substr($fullname ,0, 1, 'utf-8'); $firstname = mb_substr($fullname, 1, 10, 'utf-8'); }else{ $lastname = $fullname; } return array($lastname, $firstname); }
其中,$hyphenated這個數組存的是復姓庫。
查看本欄目