Skip to content

Instantly share code, notes, and snippets.

@shinnn
Last active December 10, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinnn/4502122 to your computer and use it in GitHub Desktop.
Save shinnn/4502122 to your computer and use it in GitHub Desktop.
Version checker in PHP (for an environment in which get_browser() is unavailable) / You can properly convert a string of version number, often including two or more periods, into a php-readable floating point number.
<?php
$agent = getenv('HTTP_USER_AGENT');
function getVersion($req){
global $agent;
preg_match(
"/(?<=".$req."[^0-9\.])([0-9]+)([0-9\._]+?)(?=[^0-9\._]|$)/i",
$agent,
$matchedStringsArr
);
if(! $matchedStringsArr){
return false;
}
$matchedStringsArr = str_replace("_", ".", $matchedStringsArr);
if(! strpos($matchedStringsArr[0], '.')){
return $matchedStringsArr[0];
}
return $matchedStringsArr[1].'.'.str_replace('.', '', $matchedStringsArr[2]);
}
?>
<?php
$agent = getenv('HTTP_USER_AGENT');
function getVersion($req){
global $agent;
preg_match(
"/(?<=".$req."[^0-9\.])([0-9]+)([0-9\._]+?)(?=[^0-9\._]|$)/i",
$agent,
$matchedStringsArr
);
//For example, $matchedStringsArr will be array("10_7_5", "10", "_7_5"), at this time.
if(! $matchedStringsArr){
return false;
}
$matchedStringsArr = str_replace("_", ".", $matchedStringsArr);
//For example, $matchedStringsArr will be array("10.7.5", "10", ".7.5"), at this time.
if(! strpos($matchedStringsArr[0], '.')){
return $matchedStringsArr[0];
}
return $matchedStringsArr[1].'.'.str_replace('.', '', $matchedStringsArr[2]);
}
var_dump(array(
$agent,
$osxVer = getVersion("Intel Mac OS X"),
$webkitVer = getVersion("Webkit"),
$chromeVer = getVersion("Chrome"),
$firefoxVer = getVersion("Firefox")
));
/*
* Output Example:
array(5) {
[0]=>
string(119) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"
[1]=>
string(5) "10.75"
[2]=>
string(6) "537.17"
[3]=>
string(10) "24.0131252"
[4]=>
NULL
}
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment