问题
I need to detect if the browser is Android (only from 1 to version 2.3), would this work?
if(preg_match('/Android [1-2.3]/', $_SERVER['HTTP_USER_AGENT'])) {
echo 'something';
}
回答1:
Following Regex can match exactly Android [1-2.3]
.
Android ([1](?:\.[0-9])?|[2](?:\.[0-3])?$)
For MSIE [6-8] Android [1-2.3]
MSIE [6-8] Android ([1](?:\.[0-9])?|[2](?:\.[0-3])?)$
Running regex here
回答2:
I don't know really know what the UserAgents for those devices look like, but the pattern you have is not likely to be what you want. I suspect you want something more along the lines of:
'/Android (1\.\d|2\.[012])/'
There are lots of different ways you could write the pattern, but essentially this one says that Android
needs to be followed by either 1.{any number}
or 2.0, 2.1 or 2.2
回答3:
I would like to suggest you use Browscap for browser detection.
get_browser
function doc http://php.net/manual/en/function.get-browser.php
'Actual' browscap .ini file downloads http://tempdownloads.browserscap.com
It should be noted that the project is closed at the moment and further update of browser-database in question.
Usage exapmle in your case:
$browser = get_browser(null, true);
if (array_key_exists('Platform', $browser) && array_key_exists('Platform_Version', $browser) && $browser['Platform'] == 'Android' && $browser['Platform_Version'] <= 2.3) {
echo 'Android <2.3 version';
}
回答4:
You can use the following regex to get the Android browser version, be it in x.x.x format or x.x. I have a regex to determine if the device is using one of the versions I'm supporting (2.3.x +):
/Android ([2].?[3-9].?[0-9]?|[3].?[0-9].?[0-9]?|[4].?[0-9].?[0-9]?)/
回答5:
From github I found this code very useful: https://gist.github.com/Abban/3939726
if(is_old_android('2.3')) {
echo 'This device has Android 2.3 or lower';
}
function is_old_android($version = '4.0.0'){
if(strstr($_SERVER['HTTP_USER_AGENT'], 'Android')){
preg_match('/Android (\d+(?:\.\d+)+)[;)]/', $_SERVER['HTTP_USER_AGENT'], $matches);
// $matches[0]= Android 4.1.2;
// $matches[1]= 4.1.2
return version_compare($matches[1], $version, '<=');
}
}
Very useful function: version_compare
来源:https://stackoverflow.com/questions/14021976/detecting-android-browser-from-v-1-to-2-3-firmware-in-php