substr() Function in PHP 8.1 & 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

The `substr()` function in PHP is used to extract a portion of a string. It returns a part of the given string starting from a specified position and optionally with a specified length. The function is available in both PHP 8.1 and PHP 8.2.

Here’s the syntax of the `substr()` function:

substr(string $string, int $start, ?int $length = null): string|false

1. `$string`: The input string from which to extract the substring.
2. `$start`: The starting position for extraction. If negative, it starts counting from the end of the string.
3. `$length` (optional): The length of the extracted substring. If omitted, the substring will extend to the end of the string.

If successful, `substr()` returns the extracted substring as a string. If an error occurs, such as invalid input parameters, it returns `false`.

Here’s an example of how to use `substr()`:

<?php
// Original string
$string = "Hello, World!";
// Extract a substring starting from position 7
$substring1 = substr($string, 7);
// Extract a substring starting from position 7 with length 5
$substring2 = substr($string, 7, 5);
// Output the extracted substrings
echo "Substring 1: $substring1<br>";
echo "Substring 2: $substring2";
?>

In this example:
1. `$substring1` extracts the substring starting from position 7 (`W`), and it continues to the end of the string.
2. `$substring2` extracts the substring starting from position 7 (`W`) with a length of 5 characters.

The output will be:

Substring 1: World!
Substring 2: World

These examples demonstrate how to use `substr()` to extract substrings from a string in PHP 8.1 and PHP 8.2.