PHP provides powerful string replacement functions that allow developers to search and replace substrings easily. The most commonly used functions are str_replace() and str_ireplace().
Both functions accept a search value, a replacement value, and the original string. They return a modified string without changing the original variable.
// Replace a substring in a case-sensitive way
<?php
$string = "Hello World";
$newString = str_replace("World", "PHP", $string);
echo $newString;
?>
The output will be Hello PHP because the substring World is replaced with PHP.
// Replace a substring ignoring case sensitivity
<?php
$string = "Hello World";
$newString = str_ireplace("world", "PHP", $string);
echo $newString;
?>
Even though world is lowercase, it matches World and produces Hello PHP.
// Replace multiple occurrences of the same word
<?php
$string = "Hello World, welcome to the World!";
$newString = str_replace("World", "PHP", $string);
echo $newString;
?>
str_replace() for exact case matchesstr_ireplace() when case does not matterstr_replace()