PHP strncasecmp字符串比较的小技巧

yipeiwu_com5年前PHP代码库
只是这样就需要转换两次。大多时候,我们是针对字符集转换的时候才会这样,比如判断参数传进来是否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个字符(大小写不敏感)。

This function returns:
这个函数将返回下列值:

0 - if the two strings are equal
0 – 如果字符串相等
<0 - if string1 is less than string2
<0 – 如果string1小于string2
>0 - if string1 is greater than string2
>0 – 如果string1大于string2
Syntax
语法
strncasecmp(string1,string2,length)
Parameter参数 Description描述
string1 Required. Specifies the first string to compare
必要参数。指定参与比较的第一个字符串对象
string2 Required. Specifies the second string to compare
必要参数。指定参与比较的第二个字符串对象
length Required. Specify the number of characters from each string to be used in the comparison
必要参数。指定每个字符串中参数比较的字符数量
Tips and Notes
注意点
Note: The strncasecmp() is binary safe and case-insensitive.
注意:strncasecmp()函数是二进制精确的,并且它不区分字母大小写。

Example
案例
复制代码 代码如下:

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

The output of the code above will be:
上述代码将输出下面的结果:
0

相关文章

PHP生成随机数的方法总结

第一种方法用mt_rand() function GetRandStr($length){ $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL...

解析smarty 截取字符串函数 truncate的用法介绍

smarty truncate 截取字符串从字符串开始处截取某长度的字符,默认的长度为80指定第二个参数作为截取字符串的长度默认情况下,smarty会截取到一个词的末尾,如果需要精确到截...

php初学者写及时补给skype用户充话费的小程序

其实加在一起有几十个,但因为需要操作的数据比较多,就在后面加了一段小程序来解决.可以处理昨天没有处理到的数据,具体如下:复制代码 代码如下:$handle = mysql_connect...

PHP实现webshell扫描文件木马的方法

本文实例讲述了PHP实现webshell扫描文件木马的方法。分享给大家供大家参考,具体如下: 可扫描 weevelyshell 生成 或加密的shell 及各种变异webshell 目前...

PHP代码维护,重构变困难的4种原因分析

本文分析讲述了PHP代码维护,重构变困难的4种原因。分享给大家供大家参考,具体如下: 代码维护,重构是件很令人不爽的一件事。以下几种情况,会让代码维护和重构变得很困难。 1. 项目开始时...