I need to find the version of Chrome using PHP.
I coded this:
$ua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.60 Safari/537.1";
preg_match( "#Chrome/([0-9]{2})#", $ua, $match );
print_r($match);
Which returns:
Array
(
[0] => Chrome/21
[1] => 21
)
I have two questions:
Will this work on all chrome browsers? (because the $ua is my own user agent.
Also how can I make the pattern so it returns only “21” instead of “Chrome/21” and “21” in an array?
This WON’T work on all Chrome browsers. What if it’s Chrome Version 3? Or Chrome Version 2245?
See me.
What I would do is change your Regular Expression to the following:
This returns the same thing as what you have now, but it also works with any-digit versions.
You can test this here.
As for your second question, you cannot modify
preg_match()to return the value like that. Simply setting$match = $match[1]works fine, though, and is completely acceptable!