2013-04-28 70 views
-2

我想更換或擴展下面的示例串未在PHP陣列preg_replace函數字符串 「的數據[KEY1] [KEY2] []」 中的 「[數據] [KEY1] [KEY2]」

"data" in "[data]" 
"data[key]" in "[data][key]" 
"data[key1][key2]" in "[data][key1][key2]" 
"data[key1][key2][]" in "[data][key1][key2]" 
"data[]" in "[data]" 

和等等。 我試了一些preg_replace,但我無法找到正確的模式

+0

這不適合你嗎? http://stackoverflow.com/questions/6088687/recursive-loop-for-multidimenional-array – 2013-04-28 06:42:13

+0

不,它不會是不是字符串不是數組 – helmi 2013-04-28 07:38:18

+2

你的問題是不是很清楚你想要什麼樣的轉換對字符串做。 「in」是什麼意思?你是否想要把「in」左邊的字符串變成_in右邊的字符串?你有沒有想方設法找到左邊的字符串,並將其替換爲右邊的字符串,反之亦然? – 2013-04-28 09:48:11

回答

0

現在的問題,你基本上想要將括號中未包含的所有單詞轉換爲封閉的單詞,並刪除空括號。

在php中,這可以在一個功能中分兩步完成!

$string = 'data 
data[key] 
data[key1][key2] 
data[key1][key2][] 
data[]'; 

$string = preg_replace(
    array('/(?<!\[)(\b\w+\b)(?!\])/', '/\[\]/'), 
    array('[$1]', ''), 
    $string); 
echo $string; 

說明:

(?<!\[)(\b\w+\b)(?!\]) 
^ ^ ^--- Negative lookahead, check if there is no ] after the word 
^  ^--- \b\w+\b 
^   ^^--- \w+ matches the occurence of [a-zA-Z0-9_] once or more 
^   ^--- \b "word boundary" check http://www.regular-expressions.info/wordboundaries.html 
    ^--- Negative lookbehind, check if there is no [ before the word 

    \[\] This basically just match [] 

Online PHP demo

相關問題