PHP Function Reference

PHP substr_compare() Function



The PHP substr_compare() function compares string from offset position with specified substring up to specified length characters.

Syntax

substr_compare(string, substring, offset, 
               length, case_insensitive)

Parameters

string Required. Specify the input string.
substring Required. Specify the substring to search for.
offset Required. Specify offset parameter which indicates where to start counting in the string. If it is negative, counting starts from the end of the string.
length Optional. Specify the maximum length after the specified offset to search for the substring. Default is the maximum of the length of the string compared to the length of substring minus the offset.
case_insensitive Optional. If set to true, comparison is case insensitive.

Return Value

Returns the following:

  • < 0 if string from position offset is less than substring
  • > 0 if string from position offset is greater than substring
  • 0 if string from position offset is equal to substring

If offset is equal to or greater than the length of string, or the length is set and is less than 0, a warning is generated and returns false.

Example: substr_compare() examples

The example below shows the usage of substr_compare() function.

<?php
//program to illustrate the substr_compare() function
echo "1. ".substr_compare("abcde", "bc", 1, 2)."\n"; 
echo "2. ".substr_compare("abcde", "BC", 1, 2, true)."\n";

echo "3. ".substr_compare("abcde", "bc", 1, 3)."\n"; 
echo "4. ".substr_compare("abcde", "cd", 1, 2)."\n"; 

echo "5. ".substr_compare("abcde", "de", -2, 2)."\n"; 
echo "6. ".substr_compare("abcde", "bcg", 1, 2)."\n"; 
?>

The output of the above code will be:

1. 0
2. 0
3. 1
4. -65793
5. 0
6. 0

Example: offset greater than length of string

When the offset is equal to or greater than the length of string, or the length is set and is less than 0, a warning is generated and returns false. Consider the example below:

<?php
$str = "ABCABCABC";

//string length
echo "string length: ".strlen($str)."\n";

//generates a warning because 10 > 9
echo substr_compare($str, 'ABCABC', 10, 3); 
?>

The output of the above code will be:

string length: 9

PHP Fatal error:  Uncaught ValueError: substr_compare(): Argument #3 ($offset) must be contained in argument #1 ($main_str) in Main.php:8
Stack trace:
#0 Main.php(8): substr_compare()
#1 {main}
  thrown in Main.php on line 8

❮ PHP String Reference