如何在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[标签]=>重复记录[名称]=> Electric Ladyland[年份]=> 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
)

你可以按你想要的方式操作数组