php 版本处理类
例如记录app版本,或某些版本数据,如果使用1.0.0这种版本格式记录入库,在需要筛选查询时会比较麻烦。
而把版本字符串转为数字保存,可以方便版本间的比较和筛选。
例如:要查询3.0.1 与 10.0.1之间的版本,因为3.0.1比10.0.1大(字符串比较),因此需要处理才可以查询。
而把 3.0.1 和 10.0.1 先转为数字 30001 和 100001来比较查询,则很方便。
version.class.php
check($version)){ list($major, $minor, $sub) = explode('.', $version); $integer_version = $major*10000 + $minor*100 + $sub; return intval($integer_version); }else{ thrownew errorexception('version validate error'); } } /** * 将数字转为版本 * @param int $version_code 版本的数字表示 * @return string */publicfunctioninteger_to_version($version_code){if(is_numeric($version_code) && $version_code>=10000){ $version = array(); $version[0] = (int)($version_code/10000); $version[1] = (int)($version_code%10000/100); $version[2] = $version_code%100; return implode('.', $version); }else{ thrownew errorexception('version code validate error'); } } /** * 检查版本格式是否正确 * @param string $version 版本 * @return boolean */publicfunctioncheck($version){$ret = preg_match('/^[0-9]{1,3}\.[0-9]{1,2}\.[0-9]{1,2}$/', $version); return$ret? true : false; } /** * 比较两个版本的值 * @param string $version1 版本1 * @param string $version2 版本2 * @return int -1:12 */publicfunctioncompare($version1, $version2){if($this->check($version1) && $this->check($version2)){ $version1_code = $this->version_to_integer($version1); $version2_code = $this->version_to_integer($version2); if($version1_code>$version2_code){ return1; }elseif($version1_code$version2_code){ return -1; }else{ return0; } }else{ thrownew errorexception('version1 or version2 validate error'); } }} // class end?>
demo.php
version_to_integer($version);echo$version_code.'
'; // 20701// 数字转版本$version = $obj->integer_to_version($version_code);echo$version.'
'; // 2.7.1// 检查版本$version = '1.1.a';var_dump($obj->check($version)); // false// 比较两个版本$version1 = '2.9.9';$version2 = '10.0.1';$result = $obj->compare($version1, $version2);echo$result; // -1?>
源码下载地址:点击查看
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了php 版本处理类,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。