我想替换或扩展以下示例字符串,而不是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,但我找不到正确的模式
现在的问题是,您基本上要将所有没有括在括号内的单词转换为括在括号内的单词,并删除空括号。
在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 []