我该如何替换一组看起来像这样的单词:
SomeText
to
Some_Text
?
我该如何替换一组看起来像这样的单词:
SomeText
to
Some_Text
?
可以轻松地通过正则表达式来实现:
$result = preg_replace('/\B([A-Z])/', '_$1', $subject);
正则表达式的简要解释:
然后我们使用 '_$1' 替换,这意味着用 [下划线 + 后向引用1] 替换匹配项。
Some_Text and Some_Other_Text and s_O_M_Em_O_R_Et_E_X_T
,而不是 SomeText and SomeOtherText and sOMEmOREtEXT
。你觉得这样可以吗? - Amil Waduwawara$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
第一个断言确保不会在字符串开头插入下划线。substr(preg_replace('/([A-Z])/', '_$1', 'SomeText'),1);
$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
?>