简体   繁体   中英

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:

{"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).

I would use preg_split using ',"' as the delimiter, but there will occasionally be a tracklisting, like this:

{"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?

It should be easy to access every item by using 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 )

I wonder why you dont want to use 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

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