Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.