2017-06-05 45 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 
*/ 
相关问题