©
本文档使用 PHP中文网手册 发布
(PHP 4, PHP 5)
strncmp — 二进制安全比较字符串开头的若干个字符
$str1
, string $str2
, int $len
)该函数与 strcmp() 类似,不同之处在于你可以指定两个字符串比较时使用的长度(即最大比较长度)。
注意该比较区分大小写。
str1
第一个字符串。
str2
第二个字符串。
len
最大比较长度。
如果 str1
小于
str2
返回 < 0;
如果 str1
大于 str2
返回 > 0;如果两者相等,返回 0。
[#1] bobvin at pillars dot net [2011-05-19 07:25:15]
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().
Here's a benchmark program to prove it:
<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
$times['strncmp'][$needle] = -microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$result = strncmp($haystack, $needle, 3) === 0;
}
$times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
$times['strpos'][$needle] = -microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$result = strpos($haystack, $needle) === 0;
}
$times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>
[#2] elloromtz at gmail dot com [2010-04-19 05:25:33]
if length is 0 regardless what the two strings are, it will return 0
<?php
strncmp("xybc","a3234",0); // 0
strncmp("blah123","hohoho", 0); //0
?>
[#3] codeguru at crazyprogrammer dot cba dot pl [2008-01-24 11:07:50]
I ran the following experiment to compare arrays.
1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))
I wanted to work out the fastest way to get the first few characters from a array
BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... - 0,000481s
if (!strncmp($key, 'HTTP_', 5)).... - 0,000405s
strncmp() is 20% faster than substr() :D
<?php
<pre>
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
{
//if (substr($key,0,5 == "HTTP_")
if (!strncmp($key, 'HTTP_', 5))
{
$out[$key] = $val;
}
}
return $out;
}
// EXAMPLE USE
?>
<?php
</pre>
print_r(strncmp_match($_SERVER));
?>
will display code like this:
Array
(
[HTTP_ACCEPT] => XXX
[HTTP_ACCEPT_LANGUAGE] => pl
[HTTP_UA_CPU] => x64
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_USER_AGENT] => Mozilla/4.0
(compatible; MSIE 7.0;
Windows NT 5.1;
.NET CLR 1.1.4322;
.NET CLR 2.0.50727)
[HTTP_HOST] => XXX.XXX.XXX.XXX
[HTTP_CONNECTION] => Keep-Alive
[HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)