2012-08-16 25 views
3

我需要一些幫助功能,我有這樣的代碼大寫每個單詞的第一個字符的字符串例外,我需要的功能,忽略了的異常,如果它是在字符串的開頭:ucwords有例外

function ucwordss($str, $exceptions) { 
$out = ""; 
foreach (explode(" ", $str) as $word) { 
$out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " "; 
} 
return rtrim($out); 
} 

$string = "my cat is going to the vet"; 
$ignore = array("is", "to", "the"); 
echo ucwordss($string, $ignore); 
// Prints: My Cat is Going to the Vet 

這就是即時通訊做:

$string = "my cat is going to the vet"; 
$ignore = array("my", "is", "to", "the"); 
echo ucwordss($string, $ignore); 
// Prints: my Cat is Going to the Vet 
// NEED TO PRINT: My Cat is Going to the Vet 
+0

順便說一句,你可以使用ucfirst而不是'strtoupper($ word {0})。 substr($ word,1)' – RiaD 2012-08-16 22:53:43

回答

4
- return rtrim($out); 
+ return ucfirst(rtrim($out)); 
+0

不錯的想法 – Ered 2012-08-16 22:51:22

1

事情是這樣的:

function ucwordss($str, $exceptions) { 
    $out = ""; 
    foreach (explode(" ", $str) as $key => $word) { 
     $out .= (!in_array($word, $exceptions) || $key == 0) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " "; 
    } 
    return rtrim($out); 
} 

甚至更簡單,在你的函數return之前進行strtoupper第一個字母

1

通過只是一直uppercasing你的第一個字難道這真的是便宜:

function ucword($word){ 
    return strtoupper($word{0}) . substr($word, 1) . " "; 
} 

function ucwordss($str, $exceptions) { 
    $out = ""; 
    $words = explode(" ", $str); 
    $words[0] = ucword($words[0]); 
    foreach ($words as $word) { 
     $out .= (!in_array($word, $exceptions)) ? ucword($word) : $word . " "; 
    } 
    return rtrim($out); 
} 
0

你怎麼樣使字符串大寫首字母等等不管你混你仍然會通過

$string = "my cat is going to the vet"; 
$string = ucfirst($string); 
$ignore = array("is", "to", "the"); 
echo ucwordss($string, $ignore); 

這樣,你該字符串的第一個字母將永遠是大寫