如何在字符串中加所有大写字母的下划线(_)infront?在大写字母之前加下划线
PrintHello将成为:Print_Hello
PrintHelloWorld将成为:Print_Hello_World
如何在字符串中加所有大写字母的下划线(_)infront?在大写字母之前加下划线
PrintHello将成为:Print_Hello
PrintHelloWorld将成为:Print_Hello_World
这是可以做到使用negative lookahead
:
$str = 'PrintHelloWorld';
$repl = preg_replace('/(?!^)[A-Z]/', '_$0', $str);
或使用positive lookahead
:
$repl = preg_replace('/.(?=[A-Z])/', '$0_', $str);
OUTPUT:
Print_Hello_World
更新:更简单办法是使用:(感谢@CasimiretHippolyte)
$repl = preg_replace('/\B[A-Z]/', '_$0', $str);
\B
比赛时不在单词边界你也有要求t o忽略第一个大写字母,所以我放入一个“负面后视”来检查它是否在字符串的开头。字符串的开头用^表示。
<?php
$string = 'PrintHelloWorld';
$pattern = '/(?<!^)([A-Z])/';
$replacement = '_$1';
echo preg_replace($pattern, $replacement, $string);
?>
下面的代码打一个链接:http://ideone.com/HvjfWW
你可以做到这一点'〜\ B [AZ]〜' –
@CasimiretHippolyte:嗯,没错,我总是忘了使用'\ B',让我更新 – anubhava