Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String substr_compare() Function



The PHP String substr_compare() function is used to compare two strings from a given start position upto a specified length. This function accepts a total of five parameters, the first three of which must be required and the remaining two optional.

Syntax

Below is the syntax of the PHP String substr_compare() function −

int substr_compare(
   string $string,
   string $search,
   int $startPos,
   ?int $length = null,
   bool $case = false
)

Parameters

Here are the parameters of the substr_compare() function −

  • $string − (Required) It is the main string where you want to search for something.

  • $search − (Required) It is the string that you want to find in the main text.

  • $startPos − (Required) It is the place you want to start your string search in the main string. If you give a negative number, it starts at the end of the main string.

  • $length − (Optional) It is the length of the main string, the $string, that you want to compare. It starts at the offset or the smaller text (search) and is by default as long as the rest of the main string.

  • $case − (Optional) It is the small and capital letters will not be compared if this is the case.

Return Value

The substr_compare() function returns -1 when the $string from position $startPos is less than the $search, 1 when it is greater than the $search, and 0 when they are equal. If $startPos is equal to or more than the $string's length, or if the $length is set and less than 0, substr_compare() returns false and gives a warning.

PHP Version

First introduced in core PHP 5, the substr_compare() function continues to function easily in PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP String substr_compare() function to compare two strings.

<?php
   echo substr_compare("tutorialspoint", "point", 2);
?>

Output

Here is the outcome of the following code −

4

Example 2

In the below PHP code we will use the substr_compare() function and compare two substrings starting at a specific position.

<?php
   // Define string here
   $mainString = "Hello World";
   $searchString = "World";

   // Compare substring
   $result = substr_compare($mainString, $searchString, 6);

   echo "Result: " . $result;
?> 

Output

This will generate the below output −

Result: 0

Example 3

Now the below code uses the substr_compare() function to compare a substring with only part of the search string.

<?php
   // Define string here
   $mainString = "Hello World";
   $searchString = "World Welcome";

   // Compare only the first 5 characters
   $result = substr_compare($mainString, $searchString, 6, 5);

   echo "Result: " . $result; 
?> 

Output

This will create the below output −

Result: 0
php_function_reference.htm
Advertisements