-2

I want to replace or extend the following sample strings not arrays in 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]"

and so on. I tried something with preg_replace but i couldt not find the correct pattern

4

1 回答 1

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 []

在线 PHP 演示

于 2013-04-28T13:36:21.323 回答