Here are some of string comparation php functions:
- strcmp($s1, $s2) – returns 0 if $s1 and $s2 are equal, a negativ value (-1) if $s1<$s2 and positive value (1) if $s1>$s2. The string comparation is case-sensitive, character by character, comparing character’s codes. Uppercase chars are considered smaller than minuscule chars. Numbers are considered smaller than letters.
- strcasecmp($s1, $s2) – idem, but the string compare is case-insensitive
- strncmp($s1, $s2, $nr) – like strcmp() but it compare only the first $nr chars of the 2 strings.
- strncasecmp($s1, $s2, $nr) – idem, case-insensitive
- strnatcmp($s1, $s2) – natural comparation, case-sensitive of the 2 strings (like natsort())
- strnatcasecmp($s1, $s2) – idem, but case-insensitive
String compare function examples
-
<?php
-
$s1 = "1 Euro";
-
$s2 = "2 Euro";
-
$s3 = "10 Euro";
-
$s4 = "10 euro";
-
echo strcmp($s1, $s2); // -1 ($s1 is alphabetically before $s2)
-
echo strcmp($s3, $s4); // -1 (the code of E char is before e char)
-
echo strcasecmp($s3, $s4); // 0 (case insensitive, the two strings are equal)
-
echo strcmp($s2, $s3); // 1 (char 1 is before 2)
-
echo strnatcmp($s2, $s3); // -1 (char 2 as number is before 10)
-
echo strncmp($s1, $s4, 1); // 0 (comparing only the first char, there is equality)
-
?>