Php preg“替换字符串”;数据[key1][key2][];在;[数据][键1][键2]”;
我想替换或扩展以下示例字符串,而不是php中的数组Php preg“替换字符串”;数据[key1][key2][];在;[数据][键1][键2]”;,php,regex,preg-replace,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做了一些尝试,但找不到正确的模式现在的问题是,你基本上想把所有没有括在括号内的单词转换成括在括号
"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;
$string='数据
数据[键]
数据[key1][key2]
数据[key1][key2][]
数据[]';
$string=preg\u replace(
数组('/(?这对你不起作用吗?不,不是字符串不是数组你的问题不是很清楚,你想对字符串做什么样的转换。你说的“in”是什么意思?你想把“in”左边的字符串取下来吗然后把它变成右边的字符串?你是想找到左边的字符串,然后换成右边的字符串,还是反过来?
(?<!\[)(\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 []