Detailed PHP Regular expression substitution implementation (PHP preg_replace,php Preg_replace) _ Regular expression

Source: Internet
Author: User
Tags arrays html tags mixed modifier php code php regular expression

What about the implementation of the PHP regular expression substitution ? First of all to introduce you to the use of php preg_replace,php preg_replace is the way we implement, then for the PHP regular expression replacement implementation process We start with the example.

The concepts associated with PHP regular expression substitution:

Preg_replace: Perform search and replace of regular expressions

Mixed Preg_replace (  
mixed pattern,  
mixed replacement,  

Preg_replace: Allows you to replace a regular expression in a string that matches to your definition.

A simple annotation removal feature:

Preg_replace (' [/*] +.+ (*)] ', ', $val ';

This code can remove a multiline annotation in PHP and CSS using the/* comment format. The three parameters are regular expressions, the string to be replaced, and the target string to replace (here to do the removal function, so it's a blank string-> '). If you want to match the subordinate rules, you can use the $ $ for all matches, $, $, and so on to represent the separate subordinate rules.

Searches the subject for a match in pattern mode and replaces it with replacement. If limit is specified, only the limit match is substituted, and if limit is omitted or the value is-1, all occurrences are replaced.

Replacement can contain//n forms or reverse references (from PHP 4.0.4) $n form, preferred to use the latter. Each such reference is replaced with the text that matches the child pattern in the nth captured bracket. n can be from 0 to 99, where//0 or $ refers to text that is matched by the entire pattern. Count the left parenthesis from left to right (starting from 1) to get the number of child modes.

A backward reference cannot be represented by a familiar//1 symbol when the replacement pattern is followed by a number (that is, a number immediately following a matching pattern) after a reverse reference. //11, for example, will make preg_replace () want a//1 reverse reference followed by a number 1 or a//11 reverse reference. In this case, the workaround is to use/${1}1. This creates an isolated, reverse reference, and the other 1 is just plain text.

A related instance of PHP regular expression substitution:

Example 1. The use of a number immediately after the reverse reference

<?php 
$string = "April, 2003"; 
$pattern = "/(/w+) (/d+), (/d+)/I"; 
$replacement = "/${1}1,/$3"; 
Print Preg_replace ($pattern, $replacement, $string); 
/* Output 
  = = 
april1,2003/ 
?>  

If a match is searched, the replaced subject is returned, otherwise the original subject is returned.

Each parameter (except the limit) of the preg_replace () can be an array. If both pattern and replacement are arrays, they are processed in the order in which their key names appear in the array. This is not necessarily the same as the numeric order of the index. If you use an index to identify which pattern will be replaced by which replacement, you should sort the array by Ksort () before calling Preg_replace ().

Example 2. Using an indexed array in Preg_replace ()

<?php 
$string =  
"The quick brown fox jumped over the lazy dog." 
$patterns [0] = "/quick/"; 
$patterns [1] = "/brown/"; 
$patterns [2] = "/fox/"; 
$replacements [2] = "Bear"; 
$replacements [1] = "BLACK"; 
$replacements [0] = "slow"; 
Print Preg_replace ($patterns, $replacements, $string); 
/* Output 
  = = = Black 
slow jumped over the lazy dog. 
* 
/* by ksorting patterns and replacements, 
  we should get what we wanted. * 
/Ksort ($patterns); 
Ksort ($replacements); 
Print Preg_replace ($patterns, $replacements, $string); 
/* Output 
  = = = = The slow black bear jumped over the 
lazy dog. 
* * 
?>  

If the subject is a group, the search and replace is performed on each item in subject and an array is returned.

If both pattern and replacement are arrays, the preg_replace () then takes the value separately from the values to search for and replace the subject. If the value in replacement is less than in pattern, the empty string is used as the remaining replacement value. If pattern is an array and replacement is a string, this string is used as the replacement value for each value in pattern. There is no point in the converse.

The/e modifier causes preg_replace () to use the replacement parameter as PHP code (after replacing the appropriate reverse reference). Tip: To make sure that replacement makes up a valid PHP code string, PHP will have a syntax resolution error in the report containing Preg_replace ().

Example 3. Replace a number of 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} = 1999-5-27"); 

This example will output:

$startDate = 5/27/1999

Example 4. Using the/e modifier

<?php 
preg_replace  
("/(<//?) (/w+) ([^>]*>)/e ", 
" '//1 '. Strtoupper ('//2 '). ' 3 ' ", 
$html _body); 

This will make all HTML tags in the input string uppercase, and the above instance runs the supported version of PHP 3>= 3.0.9, PHP 4.

PHP Regular expression to replace the relevant content to introduce you here, I hope that the understanding of you and master PHP regular expression to replace some help.

Replace content with regular expressions PHP

Before doing a project, there is a page for questions and answers, such as inserting expressions in the content of answers or questions. Written to the content of the expression is the name of the picture (and is not a suffix, such as: f_002.png) expression package placed in the project, I need to remove the content when the expression in the inside of the name to replace the image.

The content that is stored in the database is this: do not know [f_013] (the last side of this [f_013] is the expression in the database in the form of the image)

All I need to do is take the content out of the database and process the character like this in the content [f_013] into the image address, and it's obvious that you need to use regular expressions here.

1. First, I need to find this string first.

$rule = "/(?: \ [) (F_. [0-9] {1,3}) (?:\]) /I ";

This regular match will help me find the expression string.

2. After the search is to replace this string into the address of the expression picture, where a function is used as the replacement of regular expressions.

This is the function: Preg_match_all

echo Preg_replace ("/(?: \ [) (F_. [0-9] {1,3}) (?:\]) /i "," ", $line [' content ']);
$line [' content '] This is what I take out of the database,

"

Here's a very important point of knowledge: "\${1}" it's the string of expressions that are stored in the database.

\${1} = f_013

I have a complete code for my replacement here:

<?php
$result = Array ();
   $n = Preg_match_all ("/(?: \ [) (F_. [0-9] {1,3}) (?:\]) /i ", $line [' content '], $result); /* Return to find the number of strings that match the criteria *
   /if ($n = 0 | | $n = FALSE)  //If it is 0 or false to say no expression * *
{
    echo $line [' content '];
   } else
{
   echo preg_replace ("/(?: \ [) (F_. [0-9] {1,3}) (?:\]) /i ","  ", $line [' content '])
   ;
   >

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.