array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.strnatcmp.php', 1 => 'strnatcmp', ), 'up' => array ( 0 => 'ref.strings.php', 1 => '字符串 函数', ), 'prev' => array ( 0 => 'function.strnatcasecmp.php', 1 => 'strnatcasecmp', ), 'next' => array ( 0 => 'function.strncasecmp.php', 1 => 'strncasecmp', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/strings/functions/strnatcmp.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
strnatcmp — 使用自然排序算法比较字符串
该函数实现了以人类习惯对数字型字符串进行排序的比较算法,这就是“自然顺序”。注意该比较区分大小写。
string1
第一个字符串。
string2
第二个字符串。
与其他字符串比较函数类似,如果 string1
小于
string2
返回 -1
;
如果 string1
大于 string2
返回 1
;如果两者相等,返回 0
。
版本 | 说明 |
---|---|
8.2.0 |
现在此函数返回 -1 或者 1 ,之前返回负数或正数。
|
下面的例子展示了该算法与计算机常规字符串比较算法(strcmp() 所使用的)的区别:
<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>
以上示例会输出:
Standard string comparison Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order string comparison Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png )