@raphael_tillman
In PHP, you can replace a substring within a string using the str_replace()
function. Here's how to use it:
1 2 3 4 5 6 |
$string = "The quick brown fox jumps over the lazy dog"; $substring = "brown"; $replacement = "red"; $new_string = str_replace($substring, $replacement, $string); echo $new_string; // Output: "The quick red fox jumps over the lazy dog" |
In the example above, the str_replace()
function takes three arguments:
The function returns a new string with the substring replaced by the replacement string. You can assign the result to a new variable ($new_string
in the example) or replace the original string directly.
You can also use str_replace()
to replace multiple substrings at once by passing arrays of substrings and replacements. For example:
1 2 3 4 5 6 |
$string = "The quick brown fox jumps over the lazy dog"; $substr_arr = array("quick", "brown", "lazy"); $replace_arr = array("slow", "red", "energetic"); $new_string = str_replace($substr_arr, $replace_arr, $string); echo $new_string; // Output: "The slow red fox jumps over the energetic dog" |
In this example, str_replace()
replaces all occurrences of each substring in the $substr_arr
array with the corresponding replacement string in the $replace_arr
array.