简体   繁体   English

正则表达式提取php中的json响应

[英]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. 我是php的新手,正在尝试使用preg_match编写正则表达式以提取从http get获取的href值。 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. 我只想提取href值并将其传递给下一个api ...即/ 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 :( 我一直在使用http://www.solmetra.com/scripts/regex/index.php来测试我的regex ..从上一天开始就没有运气:(

please any help would be appreciated. 请任何帮助将不胜感激。

Thanks, DR 谢谢,博士

No need for a regex. 无需正则表达式。

Use json_decode() and then access the href property. 使用json_decode() ,然后访问href属性。

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. 注意:如果可能,我鼓励您清理JSON。 Particularly the keys. 特别是按键。

Don't use regex, use json_decode() . 不要使用正则表达式,请使用json_decode() JSON is an excellent example of a context-free grammar that you shouldn't even try to parse with regex. JSON是无上下文语法的一个很好的例子,您甚至不应该尝试使用正则表达式进行解析。

Here's PHP.NET's reference on using json_decode() for just this sort of thing. 这是关于使用json_decode()进行此类操作的PHP.NET 参考

Just like HTML parsing, I would recommend not using a REGEX but rather a json parser then reading the value. 就像HTML解析一样,我建议不要使用REGEX而是使用json解析器然后读取值。 Check out json_encode and json_decode functions in php. 在php中查看json_encode和json_decode函数。

That said if you just need the href value then here is a regex to do just that on the example you gave 就是说,如果您只需要href值,则可以使用正则表达式在给出的示例中执行此操作

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. 当您确切地知道所需的内容以及格式时,Regex才是正确的工具。通常无法准确预测来自其他方的json和HTML。 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. 也有某些合法的HTML和json的示例,无法使用regex进行正确的解析,因此通常使用专用的解析器对其进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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