Home  >  Article  >  Backend Development  >  PHP中比较两个字符串前n个字符是否相等的strncmp()函数使用

PHP中比较两个字符串前n个字符是否相等的strncmp()函数使用

WBOY
WBOYOriginal
2016-06-20 13:01:451177browse

PHP中strncmp()函数比较两个字符串前n个字符是否相等的方法,

分析了strncmp()函数的功能,参数用法与使用技巧,

分享给大家供大家参考,具体如下:

PHP中的strncmp()函数用于比较两个字符串(区分大小写),可判断两个字符串前n个字符是否相等。

strncmp()函数定义如下:

strncmp(string1,string2,length)

参数说明:

string1 必需。规定要比较的首个字符串。
string2 必需。规定要比较的第二个字符串。
length 必需。规定比较中所用的每个字符串的字符数。

返回值说明:

如果两个字符串相等,则返回值为 0
如果 string1 小于 string2,则返回值小于0
如果 string1 大于 string2,则返回值大于0

示例代码如下:

<?php /* strncmp()函数比较两个字符串前n个字符是否相等
 *
 * 返回值:
 0 - 如果两个字符串相等
 <0 - 如果 string1 小于 string2
 >0 - 如果 string1 大于 string2
 */
 $str1="welcome to www.jb51.net";
 $str2="WELCOME TO WWW.JB51.NET";
 $str3="welcome to php";
 echo strncmp($str1,$str2,2);
 echo "<br>";
 echo strncmp($str1,$str3,2);
?>

运行结果如下:

1
0

希望本文所述对大家PHP程序设计有所帮助。


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