2017-06-05 98 views
3

我正在使用以下代碼來對句子中的每個單詞進行大寫處理,但我無法使用附加括號的單詞進行大寫處理。如何在句子中大寫帶括號的單詞

PHP代碼:

<?php 
    $str = "[this is the {command line (interface "; 
    $output = ucwords(strtolower($str)); 
    echo $output; 

輸出:

[this Is The {command Line (interface

但是我預期的輸出應該是:

[This Is The {Command Line (Interface

如何處理帶括號的單詞? 可能有多個括號。

例如:

[{this is the ({command line ({(interface

我想找到PHP的通用解決方案/功能。

+0

查看此頁http://php.net/manual/en/function.ucwords.php –

回答

3
$output = ucwords($str, ' [{('); 
echo $output; 
// output -> 
// [This Is The {Command Line (Interface 

更新:通用的解決方案。這裏有一個「括號」 - 是任何非字母字符。 「括號」後面的任何字母都會轉換爲大寫。

$string = "test is the {COMMAND line -STRET (interface 5more 9words #here"; 
$strlowercase = strtolower($string); 

$result = preg_replace_callback('~(^|[^a-zA-Z])([a-z])~', function($matches) 
{ 
    return $matches[1] . ucfirst($matches[2]); 
}, $strlowercase); 


var_dump($result); 
// string(62) "Test Is The {Command Line -Stret (Interface 5More 9Words #Here" 

直播demo

+0

可能不希望'strtolower'。 'CLI'或'PHP'會發生什麼? – AbraCadaver

+0

好點。編輯。 –

+0

另一個我想包含數字與開始詞如何做到這一點。 示例 3s [這是命令行{接口 在這種情況下的'應該是大寫。 –

1

這是另一種解決方案,可以在for-each循環數組中,如果你要處理更多的字符添加更多的分隔符。

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<br />"); } 

//PRINTS: 
/* 
Jean-Luc Picard 
Miles O'Brien 
William Riker 
Geordi La Forge 
Beverly Crusher 
*/ 
相關問題