PHP - Replace values using preg_replace

by
Jeremy Canfield |
Updated: October 06 2022
| PHP articles
preg_replace can be used to replace values in a string. For example, let's say you have a variable that contains the text Hello World.
$string = "Hello World";
In this example, the word "Hello" is replaced with "Goodbye".
$string = preg_replace('/Hello/', 'Goodbye', $string);
Now, when you echo $string . . .
echo $string;
. . . the following will be displayed.
Goodbye World
Or, you could use a regular expression in the replacement.
$string = preg_replace('/^[A-Z]ello /', 'Goodbye', $string);
It is common to define variables for the values being used in preg_replace, like this.
$string = "Hello World";
$regex = '/^[A-Z]ello /';
$replacement = "Goodbye";
$string = preg_replace($regex, $replacement, $string);
Did you find this article helpful?
If so, consider buying me a coffee over at