2013-04-08 71 views
1

有沒有格式化人名的方法?例如,「john dOE」應該是「John Doe」。或者「安格斯macgyver」應該是「安格斯MacGyver」。等等。格式化人名 - PHP(或任何語言)庫?

我知道任何解決方案可能都不會完整(只有太多的規則來命名),但是總比沒有好。有什麼建議麼?在評論中已經建議

+0

你想加入一個大寫字母和其餘字母小寫? – 2013-04-08 21:00:53

+3

'ucfirst'和一個詞綴列表將會走很長的路。諺語20%的努力。 – Jon 2013-04-08 21:01:47

+2

不要打擾。或者按照用戶輸入的方式保留它,或者通過簡單的'ucfirst()'運行它。 – Sammitch 2013-04-08 21:01:52

回答

1

如,在PHP中,你可以做這樣的事情:

$name_formatted = ucfirst(strtolower($name_unformatted)); 

這將處理90%的情況下,你的。然後我會把它放到一個函數中,並添加規則來處理MacGuyver和O'Reilly類型的異常。

更新: 正如指出的那樣,ucfirst只能處理字符串中的第一個單詞。你可以使用正則表達式來所有大寫首字母的每一個字,或做這樣的函數:

<?php 
$name_unformatted = "JOHN DOE"; 

function format_name($name_unformatted) 
{ 
    $name_formatted = ucwords(strtolower($name_unformatted)); // this will handle 90% of the names 

    // ucwords will work for most strings, but if you wanted to break out each word so you can deal with exceptions, you could do something like this: 
    $separator = array(" ","-","+","'"); 
    foreach($separator as $s) 
    { 
     if (strpos($name_formatted, $s) !== false) 
     { 
     $word = explode($s, $name_formatted); 
     $tmp_ary = array_map("ucfirst", array_map("strtolower", $word)); // whatever processing you want to do here 
     $name_formatted = implode($s, $tmp_ary); 
     } 
    } 

    return $name_formatted; 
} 

echo format_name($name_unformatted); 
?> 

您可以在此功能擴展到處理您的名字例外。

+0

'ucfirst'不會爲JOHN DOE做任何事情。 – snoopy76 2013-04-08 21:46:24

+0

好吧,不,@ snoopy76 - 我的代碼用小寫字母表示整個字符串,然後用大寫字母表示第一個字母。我會用一個會做所有單詞的函數來更新我的答案。 – Revent 2013-04-08 22:19:26

+0

DOH!忘記了PHP中的ucwords函數。 – Revent 2013-04-08 23:57:29

1

我正在尋找一個PHP腳本,可以處理名稱的正確大小寫。雖然我知道,這將是難以處理的情況下

https://en.wikipedia.org/wiki/List_of_family_name_affixes

的100%,我覺得這個劇本做了很好的工作處理的用例的95%,至少對我們來說。這當然是一個很好的起點。

http://www.media-division.com/correct-name-capitalization-in-php/

function titleCase($string) 
{ 
    $word_splitters = array(' ', '-', "O'", "L'", "D'", 'St.', 'Mc'); 
    $lowercase_exceptions = array('the', 'van', 'den', 'von', 'und', 'der', 'de', 'da', 'of', 'and', "l'", "d'"); 
    $uppercase_exceptions = array('III', 'IV', 'VI', 'VII', 'VIII', 'IX'); 

    $string = strtolower($string); 
    foreach ($word_splitters as $delimiter) 
    { 
     $words = explode($delimiter, $string); 
     $newwords = array(); 
     foreach ($words as $word) 
     { 
      if (in_array(strtoupper($word), $uppercase_exceptions)) 
       $word = strtoupper($word); 
      else 
      if (!in_array($word, $lowercase_exceptions)) 
       $word = ucfirst($word); 

      $newwords[] = $word; 
     } 

     if (in_array(strtolower($delimiter), $lowercase_exceptions)) 
      $delimiter = strtolower($delimiter); 

     $string = join($delimiter, $newwords); 
    } 
    return $string; 
}