tags:

views:

31

answers:

1

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?

+6  A: 

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

VolkerK
I looked into that, but some people are saying it has a bunch of overhead.
polyhedron
Some people say the earth is flat. So what? ;-)
VolkerK
I started inventing this wheel before i found get_browser(), and really, I'm mad now I can't figure out this regex! So now it's a crusade about learning regex more than accomplishing the task :-). What this really boils down to us using group names in regex.
polyhedron
@VolkerK - Who says the earth is flat o_O!!! if I might add - in my previous experiance of using browsercap.ini, its never up to date enough. There tends to be a delay in new browsers and the ini file changes.
Glycerine
@Glycerine: http://en.wikipedia.org/wiki/Flat_Earth_Society and for the second argument: that's why I suggested browsers.garykeith.com which usually breaks the laws of physics by being faster-than-light ;-)
VolkerK
@polyhedron: "A bunch of overhead"? How much? What will the impact on your app be to have that "bunch of overhead"? What will the costs be to your project? CPU time is incredibly cheap. Programmer time is incredibly expensive. Make sure you're optimizing for the right thing.
Andy Lester