tags:

views:

42

answers:

2

I need extract data from a string. Heres an example:

Mozilla/5.0 (Macintosh; U; PPC Mac OS X; tr-tr) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.3

I want to get what's after the "Safari/" (417.9.3) but:

  1. The "Safari" string can be in any character case and can be anywhaere in the string.
  2. The version is separated from "Safari" by "/", " /", "/ ", " / " or any whitespace.
  3. The version string end by any whitespace, ")", "(", ";", or the end of the string.

Anyone can help me build this up?

Thanks!

+2  A: 
preg_match("#Safari(\s+|/\s*)([^)(;]+)#i", $_SERVER['HTTP_USER_AGENT'], $results);

The i at the end means "case insensitive", which answers criteria one.

(\s+|\s*/\s*)? matches either at least one whitespace character or a slash preceded and followed by an arbitrary number of whitespace characters (from zero to infinity and beyond), which addresses criteria two.

[^)(;]+ will match as many characters as possible that are not inside the set, which addresses criteria three.

zneak
For "(Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/412 (KHTML, like Gecko) Safari/412 Privoxy/3.0" your regex don't stop on the space. Why?
Activist
@Activist: because I forgot to put `\s` inside the last set (`[^();\s]+` instead of `[^();]+`). Besides, you should try to learn regular expressions. That's one really easy fix you could have done yourself if you learned how it works.
zneak
I do, slowly learning by asking questions and checking answers...
Activist
A: 

Isn't this similar to the Firefox regex that you asked for before?

/Safari[ \/]+([0-9\.]+)/i
casablanca