Skip to content

Instantly share code, notes, and snippets.

@sumardi
Created March 29, 2011 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumardi/893020 to your computer and use it in GitHub Desktop.
Save sumardi/893020 to your computer and use it in GitHub Desktop.
PHP : Extract user agent
<?php
$browser = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-us) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";
function extract_user_agent($agent)
{
$found = array();
$pattern = "([^/[:space:]]*)" . "(/([^[:space:]]*))?";
$pattern .= "([[:space:]]*\[[a-zA-Z][a-zA-Z]\])?" . "[[:space:]]*";
$pattern .= "(\\((([^()]|(\\([^()]*\\)))*)\\))?" . "[[:space:]]*";
while( strlen($agent) > 0 )
{
if ($l = preg_match($pattern, $agent, $a = array()))
{
array_push($found, array("product" => $a[1], "version" => $a[3], "comment" => $a[6]));
$agent = substr($agent, $l);
}
else $agent = "";
}
return $found;
}
echo extract_user_agent($browser);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment