2010-08-10 129 views

回答

2
<?php 
//FUNCTION 

function ucname($string) { 
    $string =ucwords(strtolower($string)); 

    foreach (array('-', '\'') as $delimiter) { 
     if (strpos($string, $delimiter)!==false) { 
     $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string))); 
     } 
    } 
    return $string; 
} 
?> 
<?php 
//TEST 

$names =array(
    'JEAN-LUC PICARD', 
    'MILES O\'BRIEN', 
    'WILLIAM RIKER', 
    'geordi la forge', 
    'bEvErly CRuSHeR' 
); 
foreach ($names as $name) { print ucname("{$name}\n"); } 

//PRINTS: 
/* 
Jean-Luc Picard 
Miles O'Brien 
William Riker 
Geordi La Forge 
Beverly Crusher 
*/ 
?> 

從關於PHP手冊條目的評論ucwords

+1

請注意,這最初降低了整個字符串,這可能是也可能不是你想要的 - 如果它不是你想要的,你總是可以刪除「strtolower」調用。 – 2010-08-10 14:53:45

1

用正則表達式:

$out = preg_replace_callback("/[a-z]+/i",'ucfirst_match',$in); 

function ucfirst_match($match) 
{ 
    return ucfirst(strtolower($match[0])); 
} 
+0

我會用'preg_replace_callback'來寫這個,但是把它打敗了.. +1 – RobertPitt 2010-08-10 14:59:02

6

你也可以使用正則表達式:

preg_replace_callback('/\b\p{Ll}/', 'callback', $str) 

\b代表一個單詞邊界和\p{Ll}介紹任何Unicode小寫字母。 preg_replace_callback將調用一個名爲callback爲每個匹配功能,並與它的返回值替換匹配:

function callback($match) { 
    return mb_strtoupper($match[0]); 
} 

這裏mb_strtoupper用於打開匹配小寫字母爲大寫。

+0

我喜歡這個,但是我認爲在像這樣的公共論壇上提倡使用/ e修飾符是有危險的,沒有經驗的程序員不會看到它的明顯危險。 – mvds 2010-08-10 15:02:29

+0

@mvds:我改用它來代替使用'preg_replace_callback'。 – Gumbo 2010-08-10 15:02:58

+0

很好,然後+1 ;-) – mvds 2010-08-10 15:03:32

3

如果您期待unicode字符......或者即使您不是,我仍建議使用mb_convert_case。當你有一個php函數時,你不需要使用preg_replace。

0

這就是我想出了(測試)...

$chars="'";//characters other than space and dash 
      //after which letters should be capitalized 

function callback($matches){ 
    return $matches[1].strtoupper($matches[2]); 
} 

$name="john doe"; 
$name=preg_replace_callback('/(^|[ \-'.$chars.'])([a-z])/',"callback",$name); 

或者,如果你有PHP 5.3+這可能是更好的(未經測試):

function capitalizeName($name,$chars="'"){ 
    return preg_replace_callback('/(^|[ \-'.$chars.'])([a-z])/', 
     function($matches){ 
      return $matches[1].strtoupper($matches[2]); 
     },$name); 
} 

我的解決辦法是有點比其他一些發佈的更詳細,但我相信它提供了最好的靈活性(您可以修改$chars字符串來更改哪些字符可以分隔名稱)。

相關問題