>我有一个示例代码:
$foo = 'hello world';
$foo = ucwords($foo); // Hello World
但是我有一个示例其他代码:
$foo = 'hello-world';
$foo = ucwords($foo);
如何结果是Hello-World
使用preg_replace_callback
$foo = 'hello-world';
$foo = ucwordsEx($foo);
echo $foo; // Hello-World
使用的功能
function ucwordsEx($str) {
return preg_replace_callback ( '/[a-z]+/i', function ($match) {
return ucfirst ( $match [0] );
}, $str );
}
现场演示
我不得不在很久以前解决这个问题。这将保留字符串中可能存在的连字符、空格和其他字符,并大写任何单词边界。
// Convert a string to mixed-case on word boundaries.
function my_ucfirst($string) {
$temp = preg_split('/('W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($temp as $key => $word) {
$temp[$key] = ucfirst($word);
}
return join ('', $temp);
}