substr_compare

(PHP 5, PHP 7, PHP 8)

substr_compareBinary safe comparison of two strings from an offset, up to length characters

Description

substr_compare(
    string $haystack,
    string $needle,
    int $offset,
    ?int $length = null,
    bool $case_insensitive = false
): int

substr_compare() compares haystack from position offset with needle up to length characters.

Parameters

haystack

The main string being compared.

needle

The secondary string being compared.

offset

The start position for the comparison. If negative, it starts counting from the end of the string.

length

The length of the comparison. The default value is the largest of the length of the needle compared to the length of haystack minus the offset.

case_insensitive

If case_insensitive is true, comparison is case insensitive.

Return Values

Returns -1 if haystack from position offset is less than needle, 1 if it is greater than needle, and 0 if they are equal. If offset is equal to (prior to PHP 7.2.18, 7.3.5) or greater than the length of haystack, or the length is set and is less than 0, substr_compare() prints a warning and returns false.

Changelog

Version Description
8.2.0 This function now returns -1 or 1, where it previously returned a negative or positive number.
8.0.0 length is nullable now.
7.2.18, 7.3.5 offset may now be equal to the length of haystack.

Examples

Example #1 A substr_compare() example

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

See Also

  • strncmp() - Binary safe string comparison of the first n characters

add a note add a note

User Contributed Notes 4 notes

up
28
jimmetry at gmail dot com
11 years ago
When you came to this page, you may have been looking for something a little simpler: A function that can check if a small string exists within a larger string starting at a particular index. Using substr_compare() for this can leave your code messy, because you need to check that your string is long enough (to avoid the warning), manually specify the length of the short string, and like many of the string functions, perform an integer comparison to answer a true/false question.

I put together a simple function to return true if $str exists within $mainStr. If $loc is specified, the $str must begin at that index. If not, the entire $mainStr will be searched.

<?php

function contains_substr($mainStr, $str, $loc = false) {
    if (
$loc === false) return (strpos($mainStr, $str) !== false);
    if (
strlen($mainStr) < strlen($str)) return false;
    if ((
$loc + strlen($str)) > strlen($mainStr)) return false;
    return (
strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}

?>
up
10
Skyborne
11 years ago
Take note of the `length` parameter: "The default value is the largest of the length of the str compared to the length of main_str less the offset."

This is *not* the length of str as you might (I always) expect, so if you leave it out, you'll get unexpected results.  Example:

<?php
$hash
= '$5$lalalalalalalala$crypt.output.here';
var_dump(substr_compare($hash, '$5$', 0)); # int(34)
var_dump(substr_compare($hash, '$5$', 0, 3)); # int(0)
var_dump(PHP_VERSION); # string(6) "5.3.14"
?>
up
3
bishop at php dot net
7 years ago
This function efficiently implements checks for strings beginning or ending with other strings:

<?php

function str_begins($haystack, $needle) {
  return
0 === substr_compare($haystack, $needle, 0, strlen($needle));
}

function
str_ends($haystack$needle) {
  return
0 === substr_compare($haystack, $needle, -strlen($needle));
}

var_dump(str_begins('http://example.com', 'https://'));

?>

Note that these are not multi-byte character set aware.
up
-12
sleek
18 years ago
Modified version of the original posted function. Use this one:

<?php
if (!function_exists('substr_compare')) {
    function
substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
       
$offset = (int) $offset;

       
// Throw a warning because the offset is invalid
       
if ($offset >= strlen($main_str)) {
           
trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
            return
false;
        }

       
// We are comparing the first n-characters of each string, so let's use the PHP function to do it
       
if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
            return
strncasecmp($main_str, $str, $length);
        }

       
// Get the substring that we are comparing
       
if (is_int($length)) {
           
$main_substr = substr($main_str, $offset, $length);
           
$str_substr = substr($str, 0, $length);
        } else {
           
$main_substr = substr($main_str, $offset);
           
$str_substr = $str;
        }

       
// Return a case-insensitive comparison of the two strings
       
if ($case_insensitivity === true) {
            return
strcasecmp($main_substr, $str_substr);
        }

       
// Return a case-sensitive comparison of the two strings
       
return strcmp($main_substr, $str_substr);
    }
}
?>
To Top