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

24

我该如何替换一组看起来像这样的单词:

SomeText

to

Some_Text

?


将 PHP 中的 exploding-uppercasedcamelcase 转换为 Upper Cased Camel Case - edorian
5个回答

40

可以轻松地通过正则表达式来实现:

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

正则表达式的简要解释:

  • \B 断言位于单词边界位置。
  • [A-Z] 匹配 A 到 Z 之间的任何大写字符。
  • () 将匹配项用后向引用编号1括起来。

然后我们使用 '_$1' 替换,这意味着用 [下划线 + 后向引用1] 替换匹配项。


你可能只能通过基准测试来确定哪个更快。差异可能微乎其微。随着正则表达式变得更加复杂,操作会变得越来越慢。 - josef.van.niekerk
这个正则表达式避免了前瞻和后顾断言,我认为这使它更快。而且更易读。它的意思是在非单词边界之后的大写字母前插入下划线。 - Billy Moon
但它返回的是 Some_Text and Some_Other_Text and s_O_M_Em_O_R_Et_E_X_T,而不是 SomeText and SomeOtherText and sOMEmOREtEXT。你觉得这样可以吗? - Amil Waduwawara
1
好的,不错的尝试 - 如果字符串是“ILovePHPAndXMLSoMuсh”,结果是:I_Love_P_H_P_And_X_M_L_So_Much,但我需要PHP和XML呢? - Arthur Kushman

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

echo $s2;  //  "This_Is_A_Test"

解释:

这个正则表达式使用两个环视断言(一个向后查找和一个向前查找)来找到字符串中应该插入下划线的位置。

(?<=[a-zA-Z])   # a position that is preceded by an ASCII letter
(?=[A-Z])       # a position that is followed by an uppercase ASCII letter
第一个断言确保不会在字符串开头插入下划线。

4
最简单的方法是使用正则表达式替换。
例如:
substr(preg_replace('/([A-Z])/', '_$1', 'SomeText'),1);

那里的substr调用是为了删除前导“_”。

4

$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

3
<?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

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接