HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

substr_compare

Description

The substr_compare of String for PHP binary safe comparison of two strings from an offset, up to length characters.

Syntax

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

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

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.

Examples

1 · haystack needle offset · negative · <

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = -8;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
-32

2 · haystack needle offset · negative · =

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = -4;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
0

3 · haystack needle offset · negative · >

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = -1;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
2

4 · haystack needle offset · non-negative · <

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = 0;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
-32

5 · haystack needle offset · non-negative · =

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = 4;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
0

6 · haystack needle offset · non-negative · >

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = 7;

$return = substr_compare($haystack, $needle, $offset);

echo $return;
2

7 · length

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = 4;
$length = 1;

$return = substr_compare($haystack, $needle, $offset, $length);

echo $return;
0

8 · case_insensitive

<?

$haystack = 'CASEcase';
$needle = 'case';
$offset = 0;
$length = 1;
$case_insensitive = true;

$return = substr_compare($haystack, $needle, $offset, $length, $case_insensitive);

echo $return;
0