How to String comparison of the first n characters (case-sensitive) in PHP ?
In PHP, there are multiple methods to compare the first n characters of two strings in a case-sensitive manner. Here are some of them:
- Using substr() and strcmp() functions: The substr() function is used to extract a substring from a string, and the strcmp() function is used to compare two strings. We can use these functions together to compare the first n characters of two strings as follows:
$str1 = "Hello World";
$str2 = "Hello PHP";
$n = 5; // number of characters to compare
if (strcmp(substr($str1, 0, $n), substr($str2, 0, $n)) === 0) {
echo "The first $n characters of $str1 and $str2 are the same.";
} else {
echo "The first $n characters of $str1 and $str2 are different.";
}
Output:
The first 5 characters of Hello World and Hello PHP are the same.
- Using substr_compare() function: The substr_compare() function is used to compare two substrings of a string. We can use this function to compare the first n characters of two strings as follows:
$str1 = "Hello World";
$str2 = "Hello PHP";
$n = 5; // number of characters to compare
if (substr_compare($str1, $str2, 0, $n) === 0) {
echo "The first $n characters of $str1 and $str2 are the same.";
} else {
echo "The first $n characters of $str1 and $str2 are different.";
}
Output:
The first 5 characters of Hello World and Hello PHP are the same.
- Using strncmp() function: The strncmp() function is used to compare the first n characters of two strings. We can use this function to compare the first n characters of two strings as follows:
$str1 = "Hello World";
$str2 = "Hello PHP";
$n = 5; // number of characters to compare
if (strncmp($str1, $str2, $n) === 0) {
echo "The first $n characters of $str1 and $str2 are the same.";
} else {
echo "The first $n characters of $str1 and $str2 are different.";
}
Output:
The first 5 characters of Hello World and Hello PHP are the same.