Skip to content

Instantly share code, notes, and snippets.

@SocalNick
Created March 27, 2012 03:21
Show Gist options
  • Save SocalNick/2212204 to your computer and use it in GitHub Desktop.
Save SocalNick/2212204 to your computer and use it in GitHub Desktop.
Jon's Cache-Control header parser
<?php
function parseValue($value)
{
$directives = array();
$lastPosition = 0;
$array = str_split($value);
while (false !== ($token = tokenizer($value, $array, ', ', $lastPosition))) {
$directive = explode('=', trim($token));
if (false === $directive) {
throw new Exception('Invalid header line for Cache-Control string: "' . $value . '"');
}
if (preg_match('/^[^a-zA-Z]{1,1}/', $directive[0])) {
throw new Exception('Invalid Cache-Control directive: "' . $token . '"');
}
$directives[$directive[0]] = true;
if (isset($directive[1])) {
if (!preg_match('/^"([^"]*)"|([^ \t",;]*)$/', $directive[1])) {
throw new Exception('Invalid Cache-Control directive: "' . $token . '"');
}
$directives[$directive[0]] = trim($directive[1], '"');
}
}
return $directives;
}
function tokenizer($string, $array, $sep, &$lastPosition)
{
$quoted = false;
$startPosition = $lastPosition;
$length = count($array);
if ($lastPosition > $length) {
return false;
}
for ($lastPosition; $lastPosition < $length; $lastPosition++) {
if (!$quoted) {
if ('"' == $array[$lastPosition]) {
$quoted = true;
} elseif (false !== strpos($sep, $array[$lastPosition])) {
if ($startPosition == $lastPosition) {
$startPosition = $lastPosition = $lastPosition++;
continue;
} else {
$lastPosition++;
break;
}
}
} else {
if ('"' == $array[$lastPosition]) {
$quoted = false;
}
}
}
return substr($string, $startPosition, $lastPosition - $startPosition);
}
try {
var_dump(parseValue('no-store& private=test, no-cache="a,b,c"'));
} catch (Exception $e) {
var_dump($e->getMessage());
}
$start = microtime(true);
for ($i=0; $i<10000; $i++) {
parseValue('no-store, private=test, no-cache="a,b,c"');
}
var_dump(microtime(true) - $start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment