Tags
Asked 3 years ago
9 Jun 2021
Views 186
debugger

debugger posted

How do I replace part of a string in PHP?

How do I replace part of a string in PHP?
rajiv

rajiv
answered Apr 25 '23 00:00

Question: What is the method for replacing a substring in PHP?

Answer: To replace a substring within a string in PHP, you can use the str_replace() function or the preg_replace() function.

The str_replace() function takes three arguments: the substring to be replaced, the replacement string, and the original string. It returns a new string with all occurrences of the substring replaced with the replacement string.

Here is an example:



$str = "The quick brown fox jumps over the lazy dog";
$new_str = str_replace("fox", "cat", $str);
echo $new_str;

Output:



The quick brown cat jumps over the lazy dog

The preg_replace() function, on the other hand, uses regular expressions to find and replace substrings in a string. This allows for more advanced and flexible string replacement.

Here is an example using preg_replace():



$str = "The quick brown fox jumps over the lazy dog";
$new_str = preg_replace("/fox/i", "cat", $str);
echo $new_str;

Output:


The quick brown cat jumps over the lazy dog

In this example, the i modifier is used to perform a case-insensitive search for the substring "fox". The preg_replace() function replaces all occurrences of the substring with the replacement string "cat".
Post Answer