在大写字母前添加下划线


Add underscore before capitalized letters

如何在字符串中所有大写字母的前面添加下划线 (_)?

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);

输出:

Print_Hello_World

更新:更简单的是使用:(感谢@CasimiretHippolyte

$repl = preg_replace('/'B[A-Z]/', '_$0', $str);
  • 'B不在单词边界时匹配

您还需要忽略第一个大写字母,因此我输入了"负面后看"以检查它是否位于字符串的开头。 字符串的开头由 ^ 表示。

<?php
$string = 'PrintHelloWorld';
$pattern = '/(?<!^)([A-Z])/';
$replacement = '_$1';
echo preg_replace($pattern, $replacement, $string);
?>

这里有一个使用代码的链接:http://ideone.com/HvjfWW