Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to detect Internet Explorer 11

I am using this preg_match string

preg_match('/Trident/7.0; rv:11.0/',$_SERVER["HTTP_USER_AGENT"]

to detect IE11 so I can enable tablet mode for it. However it returns "unknown delimiter 7".

How can I do this without PHP complaining at me?

like image 214
ben Avatar asked Nov 02 '13 14:11

ben


2 Answers

User-agent string may be reported differently across various platforms or devices. Take a look at this: http://msdn.microsoft.com/en-au/library/ie/hh869301(v=vs.85).aspx

Just found the following string pattern covering most of the User Agents as reported for IE11 or above (It may not hold true if Microsoft changes its User-agent string again for newer version of IE):

if (preg_match("/(Trident\/(\d{2,}|7|8|9)(.*)rv:(\d{2,}))|(MSIE\ (\d{2,}|8|9)(.*)Tablet\ PC)|(Trident\/(\d{2,}|7|8|9))/", $_SERVER["HTTP_USER_AGENT"], $match) != 0) {
    print 'You are using IE11 or above.';
}
like image 196
Ken Pega Avatar answered Nov 05 '22 10:11

Ken Pega


Is this really a regular expression or just a literal string? If it's just a string, you can use the strpos function instead.

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false) {
    // your code
}

If it's a regular expression, you must escape special characters like / and .

EDIT:

You can see in the comments of this answer that the code doesn't detect IE 11 properly in all cases. I didn't actually test it to match it, I've just adjusted the code of the question creator to use strpos instead of preg_match because it was applied incorrectly.

If you want a reliable way to detect IE 11 please take a look at the other answers.

like image 36
Guilherme Sehn Avatar answered Nov 05 '22 09:11

Guilherme Sehn