正则表达式匹配 - 无法解决

时间:2012-09-21 00:15:32

标签: php regex preg-match pcre

我有一个字符串,我需要在PHP中解析成一个数组。字符串看起来像这样:

(Key: ALL_HTTP)(Value:HTTP_HOST:10.1.1.1 )(Key: ALL_RAW)(Value:Host: 10.1.1.1:80 )(Key: APPL_MD_PATH)(Value:/ROOT)(Key: AUTH_TYPE)(Value:)(Key: AUTH_USER)(Value:)(Key: AUTH_PASSWORD)(Value:)(Key: LOGON_USER)(Value:)(Key: REMOTE_USER)(Value:)

“键/值”对的数量可以是无限的,但通常每串约30-40个。

我一直在使用preg_match和PHP.net中的一个示例变体 - 就像这样:

preg_match('/(\S+): (\S+)/', $string, $result);

这让我把第一把钥匙作为$ result [0],但对其余的没有帮助。

如果有人能用一个合适的表达来帮助我,这将是非常棒的。我也非常感谢用PCRE分割字符串的任何好的阅读资源。

全部谢谢!

1 个答案:

答案 0 :(得分:1)

正则表达式/\(Key:\s*(.*?)\)\(Value:\s*(.*?)\)/将匹配字符串

中的所有键/值对

该程序使用元素

中的每个键/值对构建数组$data
$str = '(Key: ALL_HTTP)(Value:HTTP_HOST:10.1.1.1 )(Key: ALL_RAW)(Value:Host: 10.1.1.1:80 )(Key: APPL_MD_PATH)(Value:/ROOT)(Key: AUTH_TYPE)(Value:)(Key: AUTH_USER)(Value:)(Key: AUTH_PASSWORD)(Value:)(Key: LOGON_USER)(Value:)(Key: REMOTE_USER)(Value:)';

$list = preg_match_all('/\(Key:\s*(.*?)\)\(Value:\s*(.*?)\)/', $str, $data);
$data = array_combine($data[1], $data[2]);

var_dump($data);

<强>输出

array(8) {
  ["ALL_HTTP"]=>
  string(19) "HTTP_HOST:10.1.1.1 "
  ["ALL_RAW"]=>
  string(18) "Host: 10.1.1.1:80 "
  ["APPL_MD_PATH"]=>
  string(5) "/ROOT"
  ["AUTH_TYPE"]=>
  string(0) ""
  ["AUTH_USER"]=>
  string(0) ""
  ["AUTH_PASSWORD"]=>
  string(0) ""
  ["LOGON_USER"]=>
  string(0) ""
  ["REMOTE_USER"]=>
  string(0) ""
}