如何在符号后大写第一个字符 - 在PHP中?

时间:2013-11-11 03:29:08

标签: php

我有一个示例代码:

$foo = 'hello world';
$foo = ucwords($foo); // Hello World

但我有其他代码示例:

$foo = 'hello-world';
$foo = ucwords($foo);

如何结果是Hello-World

2 个答案:

答案 0 :(得分:2)

使用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 );
}

Live DEMO

答案 1 :(得分:0)

我不得不在很长一段时间内解决这个问题。这将保留字符串中可能包含的连字符,空格和其他字符,并利用任何字边界。

// 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);
}
相关问题