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

I've got a string that I need to parse into an array in PHP. The string looks something like this:

(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:)

The number of "key/value" pairs could be unlimited but is usually about 30-40 per string.

I've been playing with preg_match and a variation of an example from PHP.net - something like this:

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

That gets me back the first key as $result[0] but doesn't help for the rest.

If anyone could help me with a proper expression that would be fantastic. I'd also appreciate any good reading resources for splitting strings with PCRE.

Thanks all!

Try something along the lines of

preg_match_all('/\(([^:)]+):\s*([^)]*)\)/',
        "(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:)",
        $out, PREG_SET_ORDER);

foreach ($out as $pair) {
    echo "ALL: ".$pair[0]."
";
    echo "KEY: ".$pair[1]."
";
    echo "VAL: ".$pair[2]."
";
}

You probably don't need the ALL lines.

Based on your sample string, you might like this regex better:

'/\(Key: ([^)]+)\)\(Value:([^)]*)\)/'

The regular expression /\(Key:\s*(.*?)\)\(Value:\s*(.*?)\)/ will match all the key/value pairs in the string

This program builds an array $data with the each key/value pair related in an element

$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);

output

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) ""
}