regex – Getting Browser type with PHP – Education Career Blog

I’m trying to write a class that calls back certain functions for different browsers. What I want to do is create a switch statement that accepts either (CHROME, SAFARI, FIREFOX, MSIE, etc) that is pulled from a regular expression.

I’m stumped on the regex part. I created named groups, but I can’t figure out how to get the named group that is found.

$subject = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3';

preg_match('/(?:(?P<CHROME>Chrome)|(?P<MSIE>MSIE)|(?P<IPHONE>iPhone)|(?P<FIREFOX>Firefox)|(?P<SAFARI>Safari))/', $subject, $regs);

This is what I get when this is run.

$regs = Array
(
   0 => Chrome
   CHROME => Chrome
   1 => Chrome
)

I want to switch using $regs, but the keys are all screwed up after the regex. Am I going about this the right way? How do I make sure I pull CHROME from the keys in array?

,

see get_browser()

One element of the return value is browser which seems to be what you’re looking for.
You can get an update-to-date browscap.ini (which contains the patterns to identify the browser/use agent string) from http://browsers.garykeith.com/downloads.asp

Leave a Comment