PHP: Browser version number user-agent with Version/x.x.x (Safari & Opera)
I wrote a simple class to check for user agents to display a warning for
incompatible browsers. I'm doing this server side, I know it's possible
client side.
Okey first off, I'm not much good for writing regexes..
I wrote a regex that searches for lower case browser names followed by the
version number. I do a foreach() with an array something like this:
<?php
$browsers = Array('msie','chrome','safari','firefox','opera');
foreach($browsers as $i => $browser)
{
$regex = "#({$browser})[/ ]([0-9.]*)#i";
if(preg_match($regex, $useragent, $matches))
{
echo "Browser: \"{$matches[0]}\", version: \"{$matches[1]}\"";
}
}
?>
This would yield: Browser: "Firefox", version "23.0.6".
I found this works for Firefox, MS IE, and older versions of Opera.
However some browsers like Safari and the newer versions of Opera have a
different user-agent string that contains Version/x.x.x, which is
Just to give you the an idea here are 3 user-agent strings and what I need
is highlighted.
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1
(KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14
So in each of these the following human logic correct:
If there is a Version/x.x.x in the string that is the version number.
If there isn't then Browsername/x.x.x is the version number.
Also if you look at the 1st and last user-agent string above, you can see
the Version can come before or after the browser name.
Can somebody help me to make a regex to be used with preg_match()? Do I
need to use a conditional statement or can I search for optional
groupings? I'm a bit confused..
Thanks!
No comments:
Post a Comment