True regex for getting content from parentheses in square brackets

依然范特西╮ 提交于 2019-12-24 10:42:16

问题


I love/hate the regex because of usefulness/hardness. (I don't why but I can't construct pattern :( )
I have some records in my database field like this

[(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 :))]...

Ok, I want to return an array that contain value as;

$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 :)

You can see that, number of data in the brackets and brackets number can vary

So, what is the true pattern for preg_match_all regex to collect above data?


回答1:


Try something like this:

$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);

which will print:

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 :)
        )

)

The (?R) in the regex pattern /\((?:[^()]|(?R))*\)/ is the recursive call to the entire pattern iteself.

As is clear from the comments beneath your question: it is not recommended to use such regex-voodoo in production code. My suggestion is you not store your data like the way you do in your database. Solve the issue at the root, please!




回答2:


You could do:

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

However this is impossible "Some text that can include all brackets and/or paranthesis" - how in the world would you distinguish the text from a closing parenthesis?

And in case this is a very poor data structure. First of all it's a database - it has columns, use them! Second, why are you rolling your own datastructure? You can use json, or php's serialize().

A regex is the wrong tool for this job.



来源:https://stackoverflow.com/questions/8086981/true-regex-for-getting-content-from-parentheses-in-square-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!