Usage differences between php str_replace and preg_replace

Source: Internet
Author: User
Tags html tags mixed php tutorial

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.