How to replace a substring in a string in PHP?

by raphael_tillman , in category: PHP General , a year ago

How to replace a substring in a string in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a year ago

@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:

  1. The substring you want to replace ($substring)
  2. The replacement string ($replacement)
  3. The original string you want to make the replacement in ($string)


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.