比较PHP中的两个版本字符串 [英] Compare two version strings in PHP

查看:368
本文介绍了比较PHP中的两个版本字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较两个版本格式的字符串?这样:

How to compare two strings in version format? such that:

version_compare("2.5.1",  "2.5.2") => -1 (smaller)
version_compare("2.5.2",  "2.5.2") =>  0 (equal)
version_compare("2.5.5",  "2.5.2") =>  1 (bigger)
version_compare("2.5.11", "2.5.2") =>  1 (bigger, eleven is bigger than two)

推荐答案

在PHP交互式提示中,使用 version_compare 函数,自 4.1 开始内置于PHP:

From the PHP interactive prompt using the version_compare function, built in to PHP since 4.1:

php > print_r(version_compare("2.5.1",  "2.5.2")); // expect -1
-1
php > print_r(version_compare("2.5.2",  "2.5.2")); // expect 0
0
php > print_r(version_compare("2.5.5",  "2.5.2")); // expect 1
1
php > print_r(version_compare("2.5.11", "2.5.2")); // expect 1
1

似乎PHP已经可以按照您的期望工作了.如果遇到不同的行为,也许应该指定此行为.

It seems PHP already works as you expect. If you are encountering different behavior, perhaps you should specify this.

这篇关于比较PHP中的两个版本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆