PHP substr_compare() Function
PHP substr_compare() Function
The substr_compare() function in PHP compares two strings from a specified start position. It is a binary-safe and optionally case-sensitive function.
Syntax
substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool$case_insensitivity]] )
Parameter
main_str(required)- This parameter specifies the first string to compare.
str(required)- This parameter specifies the second string to compare
offset(required)- This parameter represents the start position for the comparison. If this parameter is negative, it starts counting from the end of the string.
length(optional)- It signifies the length of the comparison.
case_insensitivity(optional)- This parameter signifies the boolean value that specifies whether to perform a case-sensitive comparison or not. If it set to true, the comparison is case insensitive else for False(default) the comparison is case-sensitive.
Return
This function returns the following values:
- 0 – if both the strings are equal
- <0 - if main_str (from offset) is less than str
- >0 - if main_str (from offset) is greater than str
If length is equal or greater than the length of main_str, this function returns FALSE.
Example 1
Output
String 1: Hello World String 2: Hello PHP The substr_compare() will return 1
Example 2
Output
717041 0 0
Example 3
str2 echo("\n"); echo substr_compare("abcdefg", "cd", 1, 2); // return -65793 ?>
Output
0 1 -65793
Example 4
Output
PHP Warning: substr_compare(): The length must be greater than or equal to zero in /workspace/Main.php on line 7