Skip to content

Instantly share code, notes, and snippets.

@jtai
Created March 27, 2012 03:53
Show Gist options
  • Save jtai/2212354 to your computer and use it in GitHub Desktop.
Save jtai/2212354 to your computer and use it in GitHub Desktop.
Cache-Control header parser
<?php
class Parser
{
public function parse($string)
{
$this->string = trim($string);
$directives = array();
// handle empty string early so we don't need a separate start state
if ($this->string == '') {
return $directives;
}
state_directive:
switch ($this->match(array('[a-z-]+'))) {
case 0:
$directive = $this->lastMatch;
goto state_value;
break;
default:
throw new Exception('expected DIRECTIVE');
break;
}
state_value:
switch ($this->match(array('="[^"]*"', '=([^",][^,]*)?'))) {
case 0:
$directives[$directive] = substr($this->lastMatch, 2, -1);
goto state_separator;
break;
case 1:
$directives[$directive] = rtrim(substr($this->lastMatch, 1));
goto state_separator;
break;
default:
$directives[$directive] = true;
goto state_separator;
break;
}
state_separator:
switch ($this->match(array('\s*,\s*', '$'))) {
case 0:
goto state_directive;
break;
case 1:
return $directives;
break;
default:
throw new Exception('expected SEPARATOR or END');
break;
}
}
private function match($tokens)
{
foreach ($tokens as $i => $token) {
if (preg_match('/^'.$token.'/', $this->string, $matches)) {
$this->lastMatch = $matches[0];
$this->string = substr($this->string, strlen($matches[0]));
return $i;
}
}
return -1;
}
}
$parser = new Parser();
print_r($parser->parse('no-store, private=test, no-cache="a,b,c"'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment