PHP Tutorial - PHP substr_compare() Function






Definition

The substr_compare() function compares two strings from a specified start position.

Syntax

PHP substr_compare() Function has the following syntax.

substr_compare(string1,string2,startpos,length,case)

Parameter

ParameterIs RequiredDescription
string1Required.First string to compare
string2Required.Second string to compare
startposRequired.Where to start comparing. If negative, it starts counting from the end of the string
lengthOptional.How long of string1 to compare
caseOptional.FALSE - Default. Case-sensitive. TRUE - Case-insensitive




Return

This function returns:

  • 0 - if the two strings are equal
  • <0 - if string1 (from startpos) is less than string2
  • >0 - if string1 (from startpos) is greater than string2

If length is equal or greater than length of string1, this function returns FALSE.





Example 1


<?php
echo substr_compare("Hello world","Hello world",0);
?>

The code above generates the following result.

Example 2

Compare two strings, when start position in string1 for the comparison is 6th:


<?php
echo substr_compare("Hello world","world",6);
?>

The code above generates the following result.

Example 3

The following code shows how to compare two strings.


//  w  ww  . j a v a  2  s.  c o m
<?php
    echo substr_compare("Hello world","Hello world",0);
    //Compare two strings, when start position in string1 for the comparison is 6th
    echo substr_compare("Hello world","world",6);
    //Using all parameters:

   echo substr_compare("world","or",1,2);
   echo substr_compare("world","ld",-2,2);
   echo substr_compare("world","orl",1,2);
   echo substr_compare("world","OR",1,2,TRUE);
   echo substr_compare("world","or",1,3);
   echo substr_compare("world","rl",1,2);


   //Different return values:

   echo substr_compare("Hello world!","Hello world!",0); // the two strings are equal
   echo substr_compare("Hello world!","Hello",0); // string1 is greater than string2
   echo substr_compare("Hello world!","Hello world! Hello!",0); // str1 is less than str2
?>

The code above generates the following result.