如何比较版本格式的两个字符串?这样:
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)
Run Code Online (Sandbox Code Playgroud)
Cha*_*les 36
从PHP交互式提示中使用该version_compare函数,自4.1以来内置到PHP :
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
Run Code Online (Sandbox Code Playgroud)
看来PHP已经按预期工作了.如果您遇到不同的行为,也许您应该指定它.
小智 6
另外,您可以通过向以下函数传递一个额外的参数来使用 PHP 内置函数:version_compare()
if(version_compare('2.5.2', '2.5.1', '>')) {
print "First arg is greater than second arg";
}
Run Code Online (Sandbox Code Playgroud)
请参阅version_compare进行进一步查询。
| 归档时间: |
|
| 查看次数: |
15003 次 |
| 最近记录: |