We can use the preg_replace() function in PHP to alter specific words or phrases within a piece of text using regular expressions.
Here's an example:
$text = "The quick brown fox jumps over the lazy dog.";
$newText = preg_replace('/brown/', 'red', $text);
echo $newText;
This code will replace the word "brown" with "red" in the $text variable, and the output will be:
"The quick red fox jumps over the lazy dog."
We can also use regular expressions to replace multiple words at once. Here's an example:
$text = "The quick brown fox jumps over the lazy dog. The brown horse runs fast.";
$newText = preg_replace('/brown|lazy/', 'red', $text);
echo $newText;
This code will replace both "brown" and "lazy" with "red" in the $text variable, and the output will be:
"The quick red fox jumps over the red dog. The red horse runs fast."
Note that we used the pipe character (|) to separate multiple words in the regular expression.
Asked: 2021-10-10 11:00:00 +0000
Seen: 11 times
Last updated: Aug 23 '21