The str_replace () function uses one string to replace other characters in the string.
Simple replacement
<? Php Tutorial
Echo str_replace ("world", "john", "hello world! ");
?>
Replace data
<? Php
Echo str_replace ("world", "john", "hello world! ");
?>
Use regular expressions to replace
Syntax: stringobj. replace (rgexp, replacetext)
Str. replace ("|", ",") only replaces the first matched character, str. replace (/|/g, ",") can replace all matched characters (g is a global sign ).
Syntax
Preg_replace (find, replace, string, count)
Preg_replace -- Search and replace regular expressions
Description
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Search for matches in pattern in subject and replace them with replacement. If limit is specified, only limit matches are replaced. If limit is omitted or its value is-1, all matches are replaced.
Instance
<? Php
$ String = "April 15,200 3 ";
$ Pattern = "/(/w +) (/d +), (/d +)/I ";
$ Replacement = "/$ {1} 1,/$3 ";
Print preg_replace ($ pattern, $ replacement, $ string );
/* Output
======
April1, 2003
*/
?>
Replace several values
<? Php
$ 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} = Maid ");
?>
This example will output:
$ Startdate = 5/27/1999
Example 4. Use the/e modifier
<? Php
Preg_replace ("/(<//?) (/W +) ([^>] *>)/e ",
"'// 1'. strtoupper (' // 2'). '// 3 '",
$ Html_body );
?>
This converts all html tags in the input string to uppercase.
The difference between preg_replace functions is mainly used for regular expressions, while str_replace functions provide better character replacement efficiency, but they are all used for character replacement functions.