Home  >  Article  >  Backend Development  >  PHP function that compares the first n characters (case-insensitive) of two strings

PHP function that compares the first n characters (case-insensitive) of two strings

黄舟
黄舟Original
2017-11-04 13:30:553314browse

Example

Compare two strings (not case sensitive):

<?php
echo strncasecmp("Hello world!","hello earth!",6);
?>

Definition and usage

strncasecmp() function compares two string (case-insensitive).

Note: strncasecmp() is binary safe and case-insensitive.

Tips: This function is similar to the strcasecmp() function, except that strcasecmp() has no length parameter.

Syntax

strncasecmp(string1,string2,length)
Parameters Description
string1 Required. Specifies the first string to compare.
string2 Required. Specifies the second string to be compared.
length Required. Specifies the number of characters per string used for comparison.

Technical details

##PHP version:

更多实例

实例 1

比较两个字符串(不区分大小写,Hello 和 hELLo 输出相同):

<?php
echo strncasecmp("Hello","Hello",6);
echo "<br>";
echo strncasecmp("Hello","hELLo",6);
?>

只是这样就需要转换两次。大多时候,我们是针对字符集转换的时候才会这样,比如判断参数传进来是否utf-8,这5个字符的写法,可就多了,比如UTF-8,Utf-8,utf-8等,那我们怎么办呢?strtolower?strupper?不需要啦。。 
strncasecmp($a,$b,$length)就可以了。。 
如果返回是0则相等,那我们怎么判断呢? 
strncasecmp($str,'utf-8',5) == 0那么,传入的参数就是utf8的,是否很方便呢? 
只是这些函数我们平时不太用得到,我看到这个函数的用法却是在 yii framework,他在处理事件的时候,判断前两个字符是否为 on 的时候,就是这样判断的。我也因此学到了一招。 

strncasecmp Definition and Usage 
定义和用法 
The strncasecmp() function compares two strings. 
strncasecmp()函数的作用是:比较字符串的前n个字符(大小写不敏感)。 

Return value: This function returns:
  • 0 - if the two strings are equal

  • ##8f029751ac12f19769820fc6523b37120 - if string1 Greater than string2

4.0.2+

The above is the detailed content of PHP function that compares the first n characters (case-insensitive) of two strings. For more information, please follow other related articles on the PHP Chinese website!

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