大写字符串的第一个字母(以特殊字符开头) - PHP

时间:2012-06-20 14:54:30

标签: php regex preg-match

我想将字符串大写为:

¿"hello"?

我希望我的函数返回

¿"Hello"?

我试过regex和preg_match,没有运气...... 这是我之前的问题,与此相关: "preg_match is matching two characters when it should only match one"

谢谢大家!

3 个答案:

答案 0 :(得分:2)

使用preg_replace_callback作为上述ascii-time,但兼容unicode:

echo preg_replace_callback('/^(\PL*)(\pL)/u', function($matches){
    return $matches[1] . mb_strtoupper($matches[2],'UTF-8');
}, '¿"éllo"?'),"\n";

<强>输出:

¿"Éllo"?

答案 1 :(得分:1)

您可以使用preg_replace_callback执行此操作:

preg_replace_callback('/^([^a-z]*)([a-z])/i', function($matches){
    return $matches[1] . strtoupper($matches[2]);
}, '¿"hello"?');

// ¿"Hello"?

答案 2 :(得分:-1)

尝试ucfirst函数http://php.net/manual/en/function.ucfirst.php

此类任务不需要正则表达式

样品

$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!