gpt4 book ai didi

PHP、正则表达式和大小写

转载 作者:搜寻专家 更新时间:2023-10-31 20:43:59 24 4
gpt4 key购买 nike

我需要将正则表达式捕获/匹配的内容大写。假设我想将连字符后的第一个字符大写,我的正则表达式将是这样的:

-(.)

我的替换字符串应该是这样的:

-\U1

preg_replace 中,我会有这样的东西:

$string = preg_replace('/-(.)/', '-\1', $string);

但这在 preg_replace 中不起作用(而且我认为它不支持在反向引用中更改大小写)。有什么建议吗?

最佳答案

您可以使用 preg_replace_callback像这样:

  $string = preg_replace_callback(
'#(?<=-)(.)#',
create_function(
'$matches',
'return strtoupper($matches[1]);'
),
$string
);

或者,使用匿名函数(使用 PHP ver >= 5.3.0):

$string = preg_replace_callback( '#(?<=-)(.)#', function( $matches) {
return strtoupper( $matches[1]);
}, $string);

现场演示:http://ideone.com/IpoCvB

关于PHP、正则表达式和大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com