繁体   English   中英

如何使用PHP中的正则表达式在字符串中搜索可以任意顺序排列的子字符串

[英]How to search a string for substrings that can be in any order using regular expressions in PHP

我目前正在使用以以下格式输出JSON数据的Web服务:

{"ID":1291,"Name":"Houses of the Holy","Artist":"Led Zeppelin","Year":1973}

但是,从一项到另一项的顺序不一致。 例如:

{"ID":2958,"Label":"Reprise Records","Name":"Electric Ladyland","Year":1968}

自然,我不能编写依赖于统一顺序属性的正则表达式,因为顺序从一个项目到另一个项目(尽管它们总是以ID开头)有所不同。

我会使用使用',“'作为分隔符的preg_split,但有时会出现跟踪列表,如下所示:

{"ID":9237,"Tracklist":[{"Track1":"Taxman","Track2":"Eleanor Rigby"}]}

...这会弄乱它。

如何使用正则表达式搜索可能以任何顺序出现或根本不出现的子字符串? 还是我必须在Web服务返回的每个项目上运行多个正则表达式,每个可能的属性都运行一个?

使用json_decode()可以轻松访问每个项目

$results = json_decode('{"ID":2958,"Label":"Reprise Records","Name":"Electric Ladyland","Year":1968}', true);
print_r($results);

输出:数组([ID] => 2958 [Label] =>重现记录[Name] => Electric Ladyland [Year] => 1968)

我不知道为什么你不想使用json_decode()

$json_string = '{"ID":1291,"Name":"Houses of the Holy","Artist":"Led Zeppelin","Year":1973}';
 $json_array =json_decode($json_string,true);

输出将是

Array
(
[ID] => 1291
[Name] => Houses of the Holy
[Artist] => Led Zeppelin
[Year] => 1973
)

然后,您可以按照所需的方式操作数组

暂无
暂无

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

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