Home>Article>Backend Development> PHP string learning: comparing two strings
in the previous article, we learned about method of splicing two strings. if necessary, please read "teach you how to use php operators splice strings together< a>". today will learn compare strings, let’s together! < p> string comparison is a common operation in string processing. there are many ways php. this article introduce three methods through code examples: use operators: built-in function strcmp()< p>< li> strcasecmp()< ul> 1. using operator strong>< can (double equal sign) or (three for equality. output result: the difference between >两个字符串相等 两个字符串相等< pre> ##="= < comparing identity operator, look see (expressions constants) value have type, i.e. both all integers so on. contain otherwise false. blockquote>we (less than) > 除了可以使用比较运算符来比较字符串外,还可以使用函数来比较字符串。php 中提供了两个函数来实现字符串比较功能,分别是 strcmp() 和 strcasecmp() 函数,我们来看看。< 2、使用内置函数strcmp()--以区分大小写的方式比较两个字符串< 如果两个字符串相等,则会返回 如果string1 小于 string2,则会返回 如果string1 大于 string2,则会返回 我们先来看下面一个例子:< strcmp($str1,$str2)." 输出: strcmp()函数在比较字符串时,是区分大小写的。< pre> 输出结果: 借助这个特性,我们可以将其运用在网站注册账号时的确认用户密码功能中(密码通常是区分大小写的),比较两次输入的密码是否一致。 只有两个字符串完全匹配,strcmp()函数才会认为相等的;而在上面示例中,$pwd1 $pwd2的大小写不同,因此两个字符串不相等。< 但有时,我们只需要比较字符串的值,不想区分大小写,例如比较网站的网址,那要怎么处理?简单,可以使用strcasecmp()函数。< 3、使用内置函数strcasecmp()--以不区分大小写的方式比较两个字符串< strcasecmp()函数和strcmp()函数类似,都可比较字符串,返回值也相同,区别只是strcasecmp()函数不区分大小写。< 下面我们来看看下面一个例子:< $url1=""//m.sbmmt.com/";" $url2=""HTTPS://WWW.PHP.CN/";" if(strcasecmp($url1, $url2)="=" 0){ '两个网址相同'; '两个网址不同'; pre> 输出结果:< >两个网址相同< pre> 好了就说到这里了,有其他想知道的,可以点击这个哦。→ →php视频教程< a>< in>
="==
" yahei, hiragino sans gb, helvetica, helvetica neue, 微软雅黑, tahoma, arial, sans-serif"> < span>< code>="==
,>
,etc.
< p>"; }else{ "两个字符串不相等
"; } ?>< pre>
" and code>="=" does not types, triple sign="==," it convert types; p>when using equality (="==)" comparison, if values are same (it only compares variables value, data type), returns true value; are same, false value.
(greater size code>
$str2){ "'$str1' 比 '$str2' 大
"; 小
"; if($str1<$str2){ pre>< p>output '12' '13' 小 '15' 大< p>php list:
comparison operator < th>name < th>description < th> tr> $a $b < td>equal to < td>if of $a $b after type conversion, return true, false < td> td>congruent < but also their types equal, then true returned, false returned < !="0){" converted conversion $b, tr>##$a $b and!="Same," tr>$a incomplete etc< if different, false< 小与< less than td>$a greater than< greater less equal< b td>##$a $b< spaceship (combination operator) < td>when than, to, an integer 0 respectively. php7 starts provide. < ?? $c null merge operator < td>the first one exists from left right and operand null. neither defined null, null returned. available starting with php7. strcmp(string1,string2)< code>比较两个字符串时,如果:<
0< code>;<
的值;< code><
> 0< code> 的值;<
"; pre>
<
< >-1< pre>
< $pwd1="'php124@qq';" $pwd2="'php124@QQ';" if(strcmp($pwd1, $pwd2) '密码不匹配!'; else { '密码匹配!'; pre>Related articles
See more