简体   繁体   English

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

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

I'm currently working with a web service that is outputting JSON data in the following format: 我目前正在使用以以下格式输出JSON数据的Web服务:

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

However, the order isn't consistent from one item to the next. 但是,从一项到另一项的顺序不一致。 For example: 例如:

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

Naturally I can't write a regular expression that depends on the attributes being in a uniform order, since the order varies from one item to the next (although they always start with ID). 自然,我不能编写依赖于统一顺序属性的正则表达式,因为顺序从一个项目到另一个项目(尽管它们总是以ID开头)有所不同。

I would use preg_split using ',"' as the delimiter, but there will occasionally be a tracklisting, like this: 我会使用使用',“'作为分隔符的preg_split,但有时会出现跟踪列表,如下所示:

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

...which would mess it up. ...这会弄乱它。

How can I use a regular expression to search for substrings that may appear in any order, or perhaps not appear at all? 如何使用正则表达式搜索可能以任何顺序出现或根本不出现的子字符串? Or will I have to run multiple regular expressions on each item the web services returns, one for each possible attribute? 还是我必须在Web服务返回的每个项目上运行多个正则表达式,每个可能的属性都运行一个?

It should be easy to access every item by using json_decode() 使用json_decode()可以轻松访问每个项目

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

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

I wonder why you dont want to use json_decode() 我不知道为什么你不想使用json_decode()

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

output will be 输出将是

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

You can then manipulate the array in way you want 然后,您可以按照所需的方式操作数组

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

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