1

由于有用性/硬度,我喜欢/讨厌正则表达式。(我不知道为什么,但我不能构造模式:()
我的数据库字段中有一些这样的记录

[(ip1=192.x.?.100)(id1=125485smds65)(date1=11.02.2011-15:00/15.06.2012-17:30)(text1=Some text that can include all brackets and/or parentheses & any chars etc, like < ( text . } , [ any ) ] { etc.**)][(ip2=x.x.20.?)(num2=1235845)(text2=many other words :))]...

好的,我想返回一个包含值的数组;

$result[ip1] = 192.x.?.100;
$result[id1] = 125485smds65;
$result[date1] = 11.02.2011-15:00/15.06.2012-17:30;
$result[text1] = Some text that can include all brackets and/or parentheses & any chars etc, like < ( text . } , [ any ) ] { etc.**;
$result[ip2] = 192.x.?.100;
$result[num2] = 1235845;
$result[text2] = many other words :)

您可以看到,括号中的数据数和括号数可以变化

那么,preg_match_all 正则表达式收集上述数据的真正模式是什么?

4

2 回答 2

4

尝试这样的事情:

$s = '(ip1=192.x.?.100)(id1=125485smds65)(date1=11.02.2011-15:00/15.06.2012-17:30)
(text1=Some text that can include all brackets and/or paranthesis & any chars etc, 
like < ( text . } , [ any ) ] { etc.**)][(ip2=x.x.20.?)(num2=1235845)
(text2=many other words :))';

preg_match_all('/\((?:[^()]|(?R))*\)/', $s, $matches);

print_r($matches);

这将打印:

Array
(
    [0] => Array
        (
            [0] => (ip1=192.x.?.100)
            [1] => (id1=125485smds65)
            [2] => (date1=11.02.2011-15:00/15.06.2012-17:30)
            [3] => (text1=Some text that can include all brackets and/or paranthesis & any chars etc, 
like < ( text . } , [ any ) ] { etc.**)
            [4] => (ip2=x.x.20.?)
            [5] => (num2=1235845)
            [6] => (text2=many other words :)
        )

)

(?R)则表达式模式/\((?:[^()]|(?R))*\)/中的 是对整个模式本身的递归调用。

从您问题下方的评论中可以清楚地看出:不建议在生产代码中使用这种 regex-voodoo。我的建议是不要像在数据库中那样存储数据。请从根本上解决问题!

于 2011-11-10T22:12:21.430 回答
0

你可以这样做:

/(\(([^)=]*)=([^)]*)\))*/

但是,这是不可能的“某些可以包含所有括号和/或括号的文本”-您到底如何将文本与右括号区分开来?

如果这是一个非常糟糕的数据结构。首先它是一个数据库——它有列,使用它们!其次,为什么要滚动自己的数据结构?您可以使用 json 或 php 的serialize().

正则表达式是这项工作的错误工具。

于 2011-11-10T22:12:17.310 回答