开发者

PHP / Regex : match json inside json

开发者 https://www.devze.com 2023-02-28 01:55 出处:网络
Just a quick regex question...hopefully I have a string that looks something like this: $string = \'some text [ something {\"index\":\"{\"index2\":\"value2\"}\"}][something2 {\"hereto be\":\"more sp

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消