How to use substr in PHP 8

Description

The substr function is useful for basic string operations like extracting the value from a color string in hexadecimal format.

substr in PHP 8

substr(string $string, int $offset, ?int $length = null): string

Parameters

The substr function returns the string specified by the offset and length parameters. The function supports various parameter cases that will affect the result.

  1. $string

    The input string to execute the function on.
  2. $offset

    • < 0: The substring will start $offset characters from the end of the string.
    • ≥ 0: The substring will start $offset characters from the start whereby 0 is the first character.
  3. $length (optional)

    If this value is omitted, the returned substring lasts till the last character.
    • < 0: The string ends $length before the end of the string.
    • > 0: The string is a most $length characters long.
    • = 0 or false: The substring is empty.

Examples

echo substr('test', 1, null);

est

In this example, the substr function removes the first character and returns the rest of the string.

echo substr('test', 1, null);

t

In this example, the substr function gets the first character of the string.