问题
I have a very important, detailed HTTP header in my response that I want to parse the value of to get the details:
Digest realm="My Very, Very Cool Site", nonce="A8W/7aDZBAA=ffc2afd053c8802dd64be69b985f38c85ec29607", algorithm=MD5, domain="/", qop="auth"
It's obviously comma-separated, but it's also quoted, so values can contain ,. There's also "Digest " that's not part of the key="value"-pairs. (I can assume the first part ("Digest") will never contain spaces, so that shouldn't be too hard.
I'm thinking the most sure way is to byte-by-byte parse and look for " and ,, but that's a lot of work.
It might be I'm missing a very useful PHP SPL function. I tried http_parse_headers(), but that's unstandard and I don't have that.
回答1:
You can use a regular expression:
function parseHeader($theHeaderValue /* Without the Digest: part */) {
if (preg_match_all("'(?<variable>[A-z0-9\_]+)\=(?<delimiter>[\"\']?)(?<value>.*?)(?<!\\\)\k<delimiter>(?:\s*(?:,|$))'isux", $theHeaderValue, $matches) and !empty($matches['variable'])) {
$result = array();
foreach ($matches['variable'] as $index=>$key) $result[$key] = $matches['value'][$index];
return $result;
} else return array();
}
来源:https://stackoverflow.com/questions/15840780/how-to-best-parse-1-http-header-value-in-php