Bootstrap FreeKB - PHP - Replace values using preg_replace
PHP - Replace values using preg_replace

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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