FreeKB - Replace values in a string in PHP (preg_replace)
Replace values in a string in PHP (preg_replace)

Home > Search

The preg_replace operator 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);

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 1d537 in the box below so that we can be sure you are a human.




Comments