PHP provides several useful functions that allow you to find and replace substrings within source strings.
substr_replace()
The substr_replace() function will replace a substring with a replacement string from a start position within a source string.
The function returns the source string with the characters from the start position to the end of the source string replaced with the replacement string.
Example of substr_replace()
<?php
$sentence = "This is the end of the sentence.";
// This prints out This is over.
echo (substr_replace ($sentence, "over", 8));
?>
An optional length argument is allowed that replaces only the stated number of characters.
Examples of substr_replace() with length argument
<?php
$sentence = "This is the end of the sentence.";
// This prints out This is the END of the sentence.
echo (substr_replace ($sentence, "END", 8, 3));
// This prints out This is NOT the end of the sentence.
echo (substr_replace ($sentence, "NOT ", 8, 0));
?>
str_replace()
The str_replace() function searches for a substring within a source string and replaces all occurrences of it with a replacement string.
Example of str_replace()
<?php
$sentence = "They say that handsome is as handsome does.";
/* This prints out
They say that ugly is as ugly does. */
echo (str_replace ("handsome", "ugly", $sentence));
?>
strtr()
The strtr() function translates characters within a source string.
Example of strtr()
<?php
$sentence = "1) - Case 1 - 2) Case 2 - 3) Case 3";
/* This prints out
a) - Case a - b) Case b - c) Case c" */
echo(strtr($sentence, "123", "abc"));
?>