2011-06-03 81 views
17

我如何更換一組字,看起來像:PHP - 前大寫字母加下劃線

SomeText 

Some_Text 

+7

爲什麼聖誕節標籤? :) – Yeroon 2011-06-03 12:27:48

+0

我的錯,對不起..但它現在已經 – Alex 2011-06-03 12:35:00

+0

*(相關)* [爆炸-uppercasedcamelcase到大寫的 - 駝峯式的PHP(http://stackoverflow.com/questions/3275837 /爆炸-uppercasedcamelcase到大寫的駝的病例中,PHP) – edorian 2011-06-03 12:42:18

回答

32

這可以容易地使用正則表達式來實現:

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

正則表達式的簡要說明:

  • \ b在字邊界斷言位置。
  • [A-Z]匹配從A-Z任何大寫字符。
  • ()包裹匹配在後面參考數字1

然後我們替換「_ $ 1」,這意味着與[下劃線+引用1]

+0

哇,這些的哪一個是快? – Alex 2011-06-03 12:31:07

+0

您可能只能通過對您的解決方案進行基準測試來判斷哪一個更快。差別可能會很小。隨着正則表達式變得越來越複雜,操作變得越來越慢。 – 2011-06-03 12:35:20

+0

這其中避免了先行和查找背後的斷言,這在我看來這使得它能更快。它也更具可讀性。只是表示在非字邊界之後的大寫字母之前插入下劃線。 – 2011-06-03 12:36:12

9
$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 

的第一個斷言確保沒有下劃線插在字符串的開始。

3

最簡單到方式更換匹配這是否與正則表達式替換。

例如:

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

的SUBSTR調用有去除領先 '_'

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 

?> 
3

$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