preg_replace字符串“data [key1] [key2] []”在“[data] [key1] [key2]”中

时间:2013-04-28 06:38:10

标签: php regex preg-replace

我想替换或扩展以下示例字符串而不是php中的数组

"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的东西,但我找不到正确的模式

1 个答案:

答案 0 :(得分: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