How do you replace occurrences of a substring within a string in PHP With Example?

Hello Friends Today, through this tutorial, I will tell you How do you replace occurrences of a substring within a string using PHP, PHP 8, PHP 8.1, PHP 8.2, PHP 8.3 With Example. In PHP, you can replace occurrences of a substring within a string using the `str_replace()` function. Here’s how you can use it:

<?php

// Original string
$string = "The quick brown fox jumps over the lazy dog.";

// Substring to be replaced
$substring_to_replace = "lazy";

// Replacement string
$replacement_string = "energetic";

// Replace occurrences of the substring
$new_string = str_replace($substring_to_replace, $replacement_string, $string);

// Output the modified string
echo $new_string;

?>

In this example, occurrences of the substring “lazy” within the original string are replaced with the string “energetic”. The `str_replace()` function takes three parameters:

1. The substring to be replaced.
2. The replacement string.
3. The original string.

It returns a new string with all occurrences of the substring replaced with the replacement string. If you want to replace multiple substrings at once, you can pass arrays for the first two parameters.