How to Use substr_replace() Function in PHP 8.1 and 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.

Hello Friends Today, through this tutorial, I will tell you How to Use `substr_replace()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. The `substr_replace()` function in PHP is used to replace a portion of a string with another string. It allows you to replace a part of a string identified by its offset and length with another string. Here’s how you can use `substr_replace()` in PHP 8.1 and 8.2 with an example:

<?php

// Syntax of substr_replace():
// substr_replace(string $original_string, string $replacement_string, int $start, ?int $length = null): string
// Example:

$original_string = "Hello, world!";
$replacement_string = "everyone";
$start = 7; // Start replacing from index 7
$length = 5; // Replace 5 characters starting from index 7
$new_string = substr_replace($original_string, $replacement_string, $start, $length);

echo $new_string; // Output: Hello, everyone!

?>

In this example:

1. `$original_string`: The original string you want to modify.
2. `$replacement_string`: The string that you want to replace the substring with.
3. `$start`: The position in the original string where the replacement will start.
4. `$length`: (Optional) The length of the substring to replace. If omitted or null, the replacement will start from the `$start` position to the end of the original string.

Make sure to adjust the values of `$start` and `$length` according to your specific use case.