Replacing Text in PHP Strings using the str_replace() Function

29-01-2023
PHP

Discover how to use PHP’s str_replace() function to replace specific text in a string with new text. This powerful function can be used to make multiple replacements at once and is useful for tasks such as sanitizing user input or updating content on a website. Learn how to use str_replace() with examples and sample code.

The str_replace() function in PHP is used to replace all occurrences of a search string with a replacement string.

Here is an example of using the str_replace() function to replace all occurrences of the name “John” with the word “Mike” in a string:


<?php
$string = "John is my best friend.";
$new_string = str_replace("John", "Mike", $string);
echo $new_string; // Output: "Mike is my best friend."
?>

In this example, the str_replace() function is used to replace the name “John” with “Mike” in the sentence.