PHP-在大写字母之前添加下划线


PHP - add underscores before capital letters

如何替换一组看起来像的单词

SomeText

Some_Text

这可以使用正则表达式轻松实现:

$result = preg_replace('/'B([A-Z])/', '_$1', $subject);

正则表达式的简要说明:

  • ''B断言单词边界处的位置
  • [A-Z]匹配A-Z中的任何大写字符
  • ()将匹配项封装在后面的参考编号1中

然后我们用'_$1'替换,这意味着用[underline+backreference1]替换匹配

$s1 = "ThisIsATest";
$s2 = preg_replace("/(?<=[a-zA-Z])(?=[A-Z])/", "_", $s1);
echo $s2;  //  "This_Is_A_Test"

说明:

regex使用两个环视断言(一个向后看,一个向前看)来查找字符串中应该插入下划线的位置。

(?<=[a-zA-Z])   # a position that is preceded by an ASCII letter
(?=[A-Z])       # a position that is followed by an uppercase ASCII letter

第一个断言确保在字符串的开头没有插入下划线。

最简单的方法是替换正则表达式。

例如:

substr(preg_replace('/([A-Z])/', '_$1', 'SomeText'),1);

那里的substr调用用于删除前导的"_"

$result = strtolower(preg_replace('/(.)([A-Z])/', '$1_$2', $subject));

转换:

HelloKittyOlolo
Declaration
CrabCoreForefer
TestTest
testTest

收件人:

hello_kitty_ololo
declaration
crab_core_forefer
test_test
test_test
<?php 
$string = "SomeTestString";
$list = split(",",substr(preg_replace("/([A-Z])/",',''1',$string),1));
$text = "";
foreach ($list as $value) {
    $text .= $value."_";
}
echo substr($text,0,-1); // remove the extra "_" at the end of the string
?>