str_replace() function uses a string to replace other characters in a string.
Simple replacement
echo str_replace("world","john","hello world!");
?>
Use regular expressions to replace
Syntax: stringobj.replace(rgexp, replacetext)
Using str.replace("|",",") will only replace the first matching character, while str.replace(/|/g,",") can replace all matching characters (g is a global flag) .
Grammar
preg_replace(find,replace,string,count)
preg_replace -- Perform regular expression search and replacement
Description
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Search subject for a match of pattern and replace with replacement. If limit is specified, only limit matches are replaced; if limit is omitted or has a value of -1, all matches are replaced.
Example
$string = "april 15, 2003";
$pattern = "/(/w+) (/d+), (/d+)/i";
$replacement = "/${1}1,/$3";
print preg_replace($pattern, $replacement, $string);/* output
======april1,2003
*/
?>
Replace several values
$patterns = array ("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/",
"/^/s*{(/w+)}/s*=/");
$replace = array ("//3///4///1//2", "$//1 =");
print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
?>
This example will output:
$startdate = 5/27/1999
Example 4. Using the /e modifier
preg_replace ("/(]*>)/e",
"'//1'.strtoupper('//2').'//3'",
$html_body);
?>
This will make all html tags in the input string uppercase
The difference is that the preg_replace function is mainly used for regular expressions and is more convenient, while str_replace is more efficient at replacing characters, but they are both functions for character replacement.