简体   繁体   中英

Regular expression to extract json response in php

I'm new to php and am trying to write a regular expression using preg_match to extract the href value that I get from my http get. The response looks:

{"_links":{"http://a.b.co/documents":{"href":"/docs"}}}

I want to extract only the href value and pass it to my next api... ie /docs. Can anyone please tell me how to extract this? I've been using http://www.solmetra.com/scripts/regex/index.php to test my regex.. and had no luck since last one day :(

please any help would be appreciated.

Thanks, DR

No need for a regex.

Use json_decode() and then access the href property.

For example:

$data = json_decode('{"_links":{"http://a.b.co/documents":{"href":"/docs"}}}', true);
echo $data['_links']['http://a.b.co/documents']['href'];

Note: I'd encourage you to clean up your JSON if possible. Particularly the keys.

Don't use regex, use json_decode() . JSON is an excellent example of a context-free grammar that you shouldn't even try to parse with regex.

Here's PHP.NET's reference on using json_decode() for just this sort of thing.

Just like HTML parsing, I would recommend not using a REGEX but rather a json parser then reading the value. Check out json_encode and json_decode functions in php.

That said if you just need the href value then here is a regex to do just that on the example you gave

preg_match('/"href":"([^"]+)"/',$string,$matches);
$matches[1];// this is the href

Regex is only the right tool when you know exactly what you want and exactly the format it will be in. Often json and HTML from other parties can't be exactly predicted. There are also examples of certain legal HTML and json which can't properly be parsed with regex so in general use a specialized parser for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM