Posts Tagged ‘RegEx’

Detection of the Internet Explorer major version number

Tuesday, December 20th, 2011

This script I just wrote is intended to fix Smarty templates for Internet Explorer
without interfering other browsers – while enabling downward compatibility.

$ua = trim(strtolower($_SERVER["HTTP_USER_AGENT"]));
$pattern = "/msie\s(\d+)\.(\d+)/";
if(preg_match($pattern,$ua,$arr)){
   $smarty->assign("ie", $arr[1]);
}

It can be used to add certain DOM nodes where required, for example:

{if $ie}IE Version: {$ie}{/if}

To load style-sheets on demand – instead of IE conditional tags:

{if $ie}
   <link rel="stylesheet" type="text/css" href="css/ie.css"/>
   <link rel="stylesheet" type="text/css" href="css/ie{$ie}.css"/>
{/if}

Or even to switch templates:

$ua = trim(strtolower($_SERVER["HTTP_USER_AGENT"]));
$pattern = "/msie\s(\d+)\.(\d+)/";
if(preg_match($pattern,$ua,$arr)){
   $smarty->display("index_ie".$arr[1].".tpl");
}
else {
   $smarty->display("index.tpl");
}

Just a quick proof of concept:

$data = array(
   'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0',
   'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
   'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0',
   'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)',
   'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)',
   'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)',
   'Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.3705)',
   'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT; .NET CLR 1.0.3705)',
   'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt; YComp 5.0.2.5; YComp 5.0.0.0)'
);
$pattern = "/msie\s(\d+)\.(\d+)/";
foreach ($data as $ua) {
   if(preg_match($pattern,strtolower($ua),$arr)){
      $major = $arr[1];
      $minor = $arr[2];
      echo $ua.' => '.$major.'.'.$minor.'<br/>';
   }
}