开发者

Regex to check IE version

I need to block IE versions upto 6. for user agent strings I wrote a regex which blocks IE 4 5 and 6. But I came across this string:

Mozilla/4.0 (c开发者_JAVA百科ompatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; TheFreeDictionary.com; FunWebProducts; FBSMTWB; GTB6; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; InfoPath.2)

In this string, there is MISE 6.0 mentioned so my regex blocks it. However it is actually IE 8 browser. So how can I construct a regex that scans for IE which is above 6 and if IE 4-5-6 appears again in the string it will ignore it.


Do not look for occurrences of MSIE 6.0 to block, detect the version as a floating point number with code like this: (You didn't specify a language so I give the example in PHP)

preg_match( '/MSIE ([0-9]{1,}[\.0-9]{0,})/', $userAgent, $matches );
$version = float( $matches[1] );
if( $version <= 6.0 ) {
    // BLOCK
}

The code above will use the first occurrence of MSIE x.x to detect the version and will ignore the rest.

UPDATE:

In Javascript:

var re = new RegExp('/MSIE ([0-9]{1,}[.0-9]{0,})/g');
if(re.exec(userString) != null) {
   version = parseFloat(RegExp.$1);
}


I'm sure you have heard a zillion times that looking into userAgent -- the process called "browser sniffing" -- does not work reliably. Browsers can and do change that string whenever and however they want. You can save yourself days of failure and endless lame explanations by forgetting about userAgent and instead using object detection, which requires no pointless calls to regex and yields a reliable result. (Read more about browser detection.)

You might want to consider using browser detection methods other than sniffing.

HTH


Are you reasonably limiting yourself to just one regexp ? Can you create a set of regexps to determine pass/fail patterns ?


Browser Sniffing gets a bad rap, and sometimes it's justified.. detecting new browsers using UA sniffing isn't a good idea. But if you are trying to detect IE5,6,7 there is a VERY good chance that it's not going to be an issue.

preg_match_all('/(MSIE\s?)(6|7)[\.0-9]{0,}/',$_SERVER['HTTP_USER_AGENT'], $matches);

Works for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜