PHP / Regex:在 json 中匹配 json
只是一个快速的正则表达式问题...希望
我有一个看起来像这样的字符串:
$string = 'some text [ something {"index":"{"index2":"value2"}"}] [something2 {"here to be":"more specific"}]';
我希望能够获得该值:
{"index":"{"index2":"value2"}"}
但是我所有匹配(或替换)的尝试都继续给我:
{"index":"{"index2":"value2"}
preg_replace('/\[(.*?)({.*?[^}]})*?\]/is', "", $string);
这里我正在匹配整个方括号区域,但希望您能看到我正在尝试做的事情。
“不匹配}”的否定似乎没有做任何事情。也许我只需要一个 OR 之类的。
嗯,谢谢你,如果你有时间回答。
$string 可以包含 {} 的多个实例,因此贪婪的正则表达式将不起作用......据我所知。
Just a quick regex question...hopefully
I have a string that looks something like this:
$string = 'some text [ something {"index":"{"index2":"value2"}"}] [something2 {"here to be":"more specific"}]';
I want to be able to get the value:
{"index":"{"index2":"value2"}"}
But all my attempts at matching (or replacing) keep giving me:
{"index":"{"index2":"value2"}
preg_replace('/\[(.*?)({.*?[^}]})*?\]/is', "", $string);
Here I'm matching the whole square bracket area, but hopefully you can see what I'm trying to do.
The negation of the "do not match }" doesn't seem to be doing anything. Maybe I just need an OR in there or something.
Well, thanks if you have time to answer.
The $string could contain multiple instances of the {} so a greedy regex won't work....that I know of.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法让正则表达式计算左括号和相应的右括号,您应该使用一个简单的 for 循环来执行此操作,但是您可以使用贪婪表达式获取从第一个左括号到最后一个右括号的完整字符串,例如:<代码>({.*})。请注意,简单的字符串函数比正则表达式快得多,因此您应该使用它们。
You can't make a regex count the opening brackets and the corresponding closeing brackets, you should use a simple for loop to do that, but you can get the complete string from the first opening bracket to the last closeing one with a greedy expression like:
({.*})
. Note that simple string functions are much faster then regular expressions, so you should use those instead.