Ask Your Question
3

How can we use regular expressions in PHP to alter specific words or phrases within a piece of text?

asked 2021-10-10 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-23 06:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-10 11:00:00 +0000

Seen: 11 times

Last updated: Aug 23 '21