Home  >  Article  >  Backend Development  >  PHP version comparison function version_compare()

PHP version comparison function version_compare()

巴扎黑
巴扎黑Original
2017-03-13 15:51:464060browse

php中比较php版本,一般用version_compare()函数。
用途:Compares two "PHP-standardized" version number strings。
语法:version_compare ( string $version1 , string $version2 [, string $operator ] )
具体描述:version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list 10bb1f83fbc487ad224e7facad35fafa, gt, >=, ge, ==, =, eq, !=, a8093152e673feb7aba1828c43532094, ne respectively.

This parameter is case-sensitive, so values should be lowercase.

    返回值:

By default, version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and1 if the second is lower.


When using the optional operator argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.

    从下面的例子,就可以很好地说明version_compare的用法:

<?php
if (version_compare(PHP_VERSION, &#39;6.0.0&#39;) >= 0) {
    echo &#39;I am at least PHP version 6.0.0, my version: &#39; . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, &#39;5.3.0&#39;) >= 0) {
    echo &#39;I am at least PHP version 5.3.0, my version: &#39; . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, &#39;5.0.0&#39;, &#39;>=&#39;)) {
    echo &#39;I am using PHP 5, my version: &#39; . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, &#39;5.0.0&#39;, &#39;<&#39;)) {
    echo &#39;I am using PHP 4, my version: &#39; . PHP_VERSION . "\n";
}
?>

    最近在nagios的图表监控插件pnp安装中遇到一个错误提示:Kohana requires PHP 5.2 or newer.查看页面源码,发现如下语句:
version_compare(PHP_VERSION, '5.2', '<') and exit('Kohana requires PHP 5.2 or newer.');
也就是版本不满足就退出。

    strcmp()的字符串比较函数,也可以进行比较,但像下面这样,就会出现错误:
4.1.10与4.1.2比较
strcmp(“4.1.10″, “4.1.2″); 会返回-1 错误
version_compare(“4.1.10″. “4.1.2″); 就会返回1 正确

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn