摘要:本文主要向大家介绍了PHP语言 版本处理类,通过具体的实例向大家展示,希望对大家学习php语言有所帮助。
本文主要向大家介绍了PHP语言 版本处理类,通过具体的实例向大家展示,希望对大家学习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
<?php/**
* 版本处理类,提供版本与数字互相转换,方便入库后进行比较筛选
* Date: 2015-06-30
* Author: fdipzone
* ver: 1.0
*
* Func:
* public version_to_integer 将版本转为数字
* public integer_to_version 将数字转为版本
* public check 检查版本格式是否正确
* public compare 比较两个版本的值
*/
class Version{ // class start
/**
* 将版本转为数字
* @param String $version 版本
* @return Int
*/
public function version_to_integer($version){
if($this->check($version)){
list($major, $minor, $sub) = explode('.', $version);
$integer_version = $major*10000 + $minor*100 + $sub;
return intval($integer_version);
}else{
throw new ErrorException('version Validate Error');
}
}
/**
* 将数字转为版本
* @param Int $version_code 版本的数字表示
* @return String
*/
public function integer_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{
throw new ErrorException('version code Validate Error');
}
}
/**
* 检查版本格式是否正确
* @param String $version 版本
* @return Boolean
*/
public function check($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:1<2, 0:相等, 1:1>2
*/
public function compare($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){
return 1;
}elseif($version1_code<$version2_code){
return -1;
}else{
return 0;
}
}else{
throw new ErrorException('version1 or version2 Validate Error');
}
}
} // class end
?>
demo.php
<?phprequire 'Version.class.php';
$version = '2.7.1';
$obj = new Version();
// 版本转数字$version_code = $obj->version_to_integer($version);echo $version_code.'<br>'; // 20701
// 数字转版本$version = $obj->integer_to_version($version_code);echo $version.'<br>'; // 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频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号