I wrote a simple class to verify that user agents display a warning for incompatible browsers. I am doing this server side, I know that this is possible on the client side.
Okey first, I'm not very good at writing regular expressions.
I wrote a regular expression that looks for browser names in lower case and then version number. I am doing foreach() with an array like :
<?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 will give: Browser: "Firefox", version "23.0.6" .
I found this for Firefox, MS IE and older versions of Opera. However, some browsers, such as Safari and later versions of Opera, have a different user agent line that contains the / xxx version, which
Just to give you an idea, here are 3 lines of the user agent, 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.1Mozilla/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 them the correct logic:
- If the line has a
Version/ xxx number, which is the version number. - If not, then
Browsername/ xxx is the version number.
Also, if you look at the first and last line of the user agent above, you can see that Version may appear before or after the browser name.
Can someone help me make a regex for use with preg_match() ? Do I need to use a conditional operator or can I find additional groups? I'm a little confused.
Thanks!
Edit 09-17-2013: I forgot to mention that I do not want to use get_browser() , it uses a huge library to detect the capabilities of browsers, etc. I only need a short “white list” of browsers, which should take several milliseconds, and not several hundred ms, to read cap.ini files for viewing. Otherwise, George’s answer would be the answer.