如何在PHP中最好地解析1个HTTP头VALUE? [英] How to best parse 1 HTTP header VALUE in PHP?
问题描述
我的回复中有一个非常重要的详细HTTP标头,我想要解析其值以获取详细信息:
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"
它显然以逗号分隔,但它也被引用,因此值可以包含,
。还有Digest
这不是 key =value
-pairs的一部分。 (我可以假设第一部分(摘要)永远不会包含空格,所以这不应该太难。
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.
可能我错过了一个非常有用的PHP SPL函数。我试过 http_parse_headers()
,但那是不标准的我没有那个。
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.
推荐答案
你可以使用正则表达式:
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();
}
这篇关于如何在PHP中最好地解析1个HTTP头VALUE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!