使用正则表达式和preg_replace_callback

时间:2012-06-21 07:28:48

标签: php regex preg-replace-callback

我想把字符串的第一个字母大写,这个字符串可能有特殊字符(这就是ucfirst在这里无效的原因)。我有下一个代码:

$string = 'ésta';
$pattern = '/^([^a-z]*)([a-z])/i';

$callback_fn = 'process';

echo preg_replace_callback($pattern, $callback_fn, $string);


function process($matches){
    return $matches[1].strtoupper($matches[2]);
}

返回'éSta',但'Ésta'是预期的......我认为我的问题是我正在使用的模式,但我做了不同的组合(如$pattern = '/\pL/u')但我找不到好的正则表达式。有人能帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:2)

这是因为您的a-z与é不匹配。编写正则表达式以包含unicode字符可能很困难。

从您的代码中,它只会将第一个字母大写,无论字符串中的单词数量多少。如果是这样,那就这样做:

$string = 'ésta';
$ucstring = ucphrase($string);

function ucphrase($word) {
  return mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
}

mb_*函数应正确处理您的特殊字符。


根据您的评论,我了解您的困境。在这种情况下,您可以使用正则表达式,但使用正确的unicode选择器

$string = 'ésta';
$pattern = '/(\p{L})(.+)/iu';

$callback_fn = 'process';

echo preg_replace_callback($pattern, $callback_fn, $string);


function process($matches){
    return mb_strtoupper($matches[1], 'UTF-8') . $matches[2];
}