Latest web development tutorials

PHP substr_compare () function

PHP String Reference PHP String Reference

Examples

Compare two strings:

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

Running instance »

Definition and Usage

() Function compares two strings from the specified start position substr_compare.

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


grammar

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

参数 描述
string1 必需。规定要比较的第一个字符串。
string2 必需。规定要比较的第二个字符串。
startpos 必需。规定在 string1 中的何处开始比较。如果为负数,则从字符串末端开始计数。
length 可选。规定在 string1 中参与比较的字符数。
case 可选。一个布尔值,规定是否执行区分大小写的比较:
  • FALSE - 默认。区分大小写
  • TRUE - 不区分大小写

technical details

return value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 (from a starting position startpos) less than string2
  • > 0 - if string1 (from a starting position startpos) is greater than string2
If the length is greater than or equal to the length of string1, the function returns FALSE.
PHP version: 5+
Update log: Since PHP 5.1 onwards, allows the use of negative startpos.


More examples

Example 1

Compare two strings, string1 for the starting position when the comparison is 6:00:

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

Running instance »

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

Running instance »

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

Running instance »


PHP String Reference PHP String Reference