How to best parse 1 HTTP header VALUE in PHP?

亡梦爱人 提交于 2019-12-14 03:36:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!