PHP String substr_compare() Function
The substr_compare() is a built-in function of PHP, which helps to compare the two strings from a specified start position to specified end position. This function is a binary-safe function and optionally case-sensitive. PHP 5 and above versions support this function.
The syntax of substr_compare() function is given below.
It consists of five parameters in which three are mandatory, and the remaining two are optional. Below is the description for these parameters:
$main_str (required): It is the main string parameter of this function which needs to be compared. It is a mandatory parameter.
$str (required): It is the second string parameter of this function which is specified to be compared. It is also a mandatory parameter as main_str.
$start_pos (required): It is a mandatory parameter, which has an integer value. This parameter specifies the value, where to start a comparison of $str in $main_str. In other words, - it provides the start position for the comparison.
If the passed value is negative, then it starts comparing from the end of the string.
$length (optional): This parameter is not mandatory to pass in this function. It consists the length of the comparison, means it specifies how much of $str to compare.
$case-insensitivity (optional): This parameter contains the Boolean value, which specifies whether to perform case-sensitive comparison or not. It is an optional parameter as $length. If case-insensitivity is TRUE, then the comparison will be case-insensitive.
This function returns the following values:
Return 0 - If both the given strings are equal.
Return < 0 - If $main_str (from start position) is less than $str.
Return > 0 - If $main _str (from start position) is greater than $str.
Note: If $length parameter value is equal and greater than the length of the main string ($main_str), then this function displays a warning and will return FALSE.
Below few numbers of examples are given to learn the working of substr_compare() function.
In the below example, we are passing 3 mandatory parameters in this function. Lets's see the working of substr_compare() with three arguments.
0 11 -5
11 0 -1
0 1 -1
Example 4: Case-sensitive/insensitive
In the below example, we are passing all the five parameters in this function. Lets's see the working of substr_compare() with all arguments.
0 1 0