Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用带有preg_replace_回调的正则表达式_Php_Regex_Preg Replace Callback - Fatal编程技术网

Php 使用带有preg_replace_回调的正则表达式

Php 使用带有preg_replace_回调的正则表达式,php,regex,preg-replace-callback,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].st

我想将字符串的第一个字母大写,它可以有特殊字符(这就是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]);
}

返回“Esta”但预期为“Esta”。。。我想我的问题是我使用的模式,但是我做了不同的组合(比如
$pattern='/\pL/u'
),但是我没有找到一个好的正则表达式。

这是因为你的
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];
}

我的问题是,它并不总是我必须大写的第一个字母,因为我的字符串可能是类似于“?”esta“?”的东西,我希望我的函数返回“?”esta“?”非常感谢!!;)