Simple User Agent string parser
<?php
class UserAgentStringParser
{
/**
* Extracts information from the user agent string.
*
* @param string $string The user agent string
* @return array Returns the user agent information.
*/
public function parse($string)
{
$userAgent = array(
'string' => $this->cleanUserAgentString($string),
'browser_name' => null,
'browser_version' => null
);
if (empty($userAgent['string'])) {
return $userAgent;
}
// Find the right name/version phrase (or return empty array if none found)
foreach ($this->getKnownBrowsers() as $browser => $regex) {
// Build regex that matches phrases for known browsers (e.g. "Firefox/2.0" or "MSIE 6.0").
// This only matches the major and minor version numbers (e.g. "2.0.0.6" is parsed as simply "2.0").
$pattern = '#'.$regex.'[/ ]+([0-9]+(?:\.[0-9]+)?)#';
if (preg_match($pattern, $userAgent['string'], $matches)) {
$userAgent['browser_name'] = $browser;
if (isset($matches[1])) {
$userAgent['browser_version'] = $matches[1];
}
break;
}
}
return $userAgent;
}
/**
* Gets known browsers. Since some UAs have more than one phrase we use an ordered array to define the precedence.
*
* @return string[]
*/
protected function getKnownBrowsers()
{
return array(
'firefox' => 'firefox',
'opera' => 'opera',
'edge' => 'edge',
'msie' => 'msie',
'chrome' => 'chrome',
'safari' => 'safari',
// ...
);
}
/**
* Gets known browser aliases.
*
* @return array
*/
protected function getKnownBrowserAliases()
{
return array(
'opr' => 'opera',
'iceweasel' => 'firefox',
// ...
);
}
/**
* Make user agent string lowercase, and replace browser aliases.
*
* @param string $string The dirty user agent string
* @return string Returns the clean user agent string.
*/
protected function cleanUserAgentString($string)
{
// clean up the string
$string = trim(strtolower($string));
// replace browser names with their aliases
$string = strtr($string, $this->getKnownBrowserAliases());
return $string;
}
}