Home > Backend Development > PHP Tutorial > Differences in usage between php str_replace and preg_replace_PHP tutorial

Differences in usage between php str_replace and preg_replace_PHP tutorial

WBOY
Release: 2016-07-20 11:02:39
Original
1103 people have browsed it

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.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445351.htmlTechArticlestr_replace() function uses a string to replace other characters in the string. Simple replacement echo str_replace(world,john,hello world!); ? Use regular expressions to replace syntax: s...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template