PHP/String/strcmp
Содержание
Comparing strings with strcmp()
<source lang="html4strict">
<? $x = strcmp("x54321","x5678"); if ($x > 0) {
print ""x54321" is greater than the string "x5678".";
} elseif ($x < 0) {
print ""x54321" is less than the string "x5678".";
} $x = strcmp("54321","5678"); if ($x > 0) {
print ""54321" is greater than the string "5678".";
} elseif ($x < 0) {
print ""54321" is less than the string "5678".";
} $x = strcmp("6 p","55 c"); if ($x > 0) {
print ""6 p" is greater than than the string "55 c".";
} elseif ($x < 0) {
print ""6 p" is less than the string "55 c".";
} $x = strcmp("6 pack",55); if ($x > 0) {
print "The string "6 pack" is greater than the number 55.";
} elseif ($x < 0) {
print "The string "6 pack" is less than the number 55.";
} ?>
</source>
For example, using my collation rules (Canadian-English), I obtain the following results:
<source lang="html4strict">
echo strcmp ("Apple", "Banana"); // returns < 0 echo strcmp ("apple", "Apple"); // returns > 0 echo strcmp ("1", "test"); // returns < 0
</source>
int strcmp ( string str1, string str2 ), case-insensitive sibling, strcasecmp( )
<source lang="html4strict">
<?
$string1 = "foo"; $string2 = "bar"; $result = strcmp($string1, $string2); switch ($result) { case -1: print "Foo comes before bar"; break; case 0: print "Foo and bar are the same"; break; case 1: print "Foo comes after bar"; break; }
?>
</source>
strcmp() function performs a case-sensitive comparison of two strings.
<source lang="html4strict">
Its syntax follows: int strcmp (string string1, string string2) strcmp() returns one of three possible values: 0 if string1 and string2 are equal < 0 if string1 is less than string2 > 0 if string2 is less than string1 <? $string1 = "butter"; $string2 = "butter"; if ((strcmp($string1, $string2)) == 0) :
print "Strings are equivalent!";
endif; ?>
</source>