PHP substr_compare()Functions

PHP String 参考手册PHP String Reference Manual

Examples

Compare two strings:

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

Run example »

Definition and Usage

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

Tip:This function is binary-safe and optionally case-sensitive.


Syntax

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

Parameter Description
string1 Required. Specifies the first string to compare.
string2 Required. Specifies the second string to compare.
startpos Required. Specifies where to start comparing in string1. If negative, it starts counting from the end of the string.
length Optional. Specifies the number of characters to compare in string1.
case Optional. A boolean value that specifies whether to perform a case-sensitive comparison:
  • FALSE - Default. Case-sensitive
  • TRUE - Case-insensitive

Technical Details

Return Value: This function returns:
  • 0 - If the two strings are equal
  • <0 - If string1 (from the start position startpos) is less than string2
  • >0 - If string1 (from the start position startpos) is greater than string2
If length is greater than or equal to the length of string1, the function returns FALSE.
PHP Version: 5+
Changelog: As of PHP 5.1, negative numbers are allowed forstartpos。


More Examples

Example 1

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

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

Run example »

Example 2

Use all parameters:

<?php
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);
?>

Run example »

Example 3

Different return values:

<?php
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
?>

Run example »


PHP String 参考手册PHP String Reference Manual Other Extensions