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
?>
strncmp
(PHP 4, PHP 5)
strncmp — Бинарно-безопасное сравнение первых n символов строк
Описание
int strncmp
( string
$str1
, string $str2
, int $len
)Эта функция подобна strcmp(), за исключением того, что можно указать максимальное количество символов в обоих строках, которые будут участвовать в сравнении.
Эта функция учитывает регистр символов.
Список параметров
-
str1 -
Первая строка.
-
str2 -
Вторая строка.
-
len -
Количество символов, используемых в сравнении.
Возвращаемые значения
Возвращает отрицательное число, если str1
меньше, чем str2, положительное число,
если str1 больше, чем
str2, и 0 если строки равны.
Смотрите также
- strncasecmp() - Бинарно-безопасное сравнение первых n символов строк без учета регистра
- preg_match() - Выполняет проверку на соответствие регулярному выражению
- substr_compare() - Бинарно-безопасное сравнение 2 строк со смещением, с учетом или без учета регистра
- strcmp() - Бинарно-безопасное сравнение строк
- strstr() - Находит первое вхождение подстроки
- substr() - Возвращает подстроку
elloromtz at gmail dot com ¶
3 years ago
codeguru at crazyprogrammer dot cba dot pl ¶
5 years ago
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
// 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
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>
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)
)
bobvin at pillars dot net ¶
2 years ago
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);
?>
Anonymous ¶
4 months ago
Returns FALSE if $len is negative or NAN.
Floating point values for $len are rounded towards 0.
Anonymous ¶
11 years ago
strncmp("sample","sam",4) returns 1 because the final requirement is if one string terminates before len, then the other must also terminate at that position.
You can imagine that all your strings have one more final, invisible "termination" character. If that termination character happens to be within in len, then it must match, too.
For instance, write that termination character with, say, the sequence "\0". Then you can equivalently consider that function call as strncmp("sample\0","sam\0",4).
So, the "p" in "sample" does not match the termination character in "sam".
