我使用以下代码来大写句子中的每个单词,但我无法将附加括号的单词大写。
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 :(得分: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
答案 1 :(得分: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
*/