真正的正则表达式在方括号中括号中的内容得到 [英] True regex for getting content from parentheses in square brackets

查看:366
本文介绍了真正的正则表达式在方括号中括号中的内容得到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我爱/恨,因为效用/硬度的正则表达式。 (我不知道为什么,但我不能构造格局:()结果
我在我的数据库字段的一些记录这样的结果。

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)(日期1 = 11.02.2011-15:00 / 15.06.2012-17:30)(文本1 =写一些文字这可以包括所有括号和/或圆括号和放大器;任何字符等,像<?(文字},[任意){等**)] [(IP2 = xx20)(NUM2 = 1235845)(文本2 =许多话:))] ... 搜索

好吧,我想返回包含值作为一个数组;结果

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

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

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

推荐答案

尝试是这样的:

$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))* \\ )/ 是整个模式iteself递归调用。

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

由于是从你的问题下面的意见明确:它不建议在生产中使用code这样的正则表达式,巫术。我的建议是你的的存储就像你在你的数据库的方式做你的数据。解决这一问题的根源,请!

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!

这篇关于真正的正则表达式在方括号中括号中的内容得到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆