Home>

How does php regular expression replacement work?First introduce you to php preg_replace. The use of php preg_replace is our method.So for the implementation of PHP regular expression replacement, we start with an example,Follow us if you are interested.

PHP regular expression replacement implementationHow is it?First introduce you tophp preg_replace, php preg_replaceThe use is our method,So for the PHP regular expression replacement implementation process we start with an example.

Related concepts of php regular expression replacement:

preg_replace:Perform regular search and replace

mixed preg_replace (
mixed pattern,mixed replacement,mixed subject [, int limit])
</pre>
</div>
<p>
preg_replace:allows you to replace a regular expression in a string that matches your definition.
</p>
<p>
A simple annotation removal function:
</p>
<p>
preg_replace ("[(/*)+.+(*/)]", "", $val);
</p>
<p>
This code can remove multiple lines of comments using the/* comment */format in php and css.
The three parameters are regular expressions,The string to be replaced with and the target string to be replaced (here to remove the function,So it's a blank string->""). If i want to match secondary rules,You can use $0 for all matches,$1, $2, and so on, and so on to represent the respective secondary rules.
</p>
<p>
Search for a match for pattern in subject and replace it with replacement. If limit is specified, only limit matches are replaced. If limit is omitted or its value is -1, all matches are replaced.
</p>
<p>
replacement can contain backreferences of the form //n or (as of PHP 4.0.4) $n
The latter is preferred.
Each such reference will be replaced with text that matches the subpattern in the nth captured parenthesis.
n can be from 0 to 99, where //0 or $0 refers to text that is matched by the entire pattern.
Count the left parentheses from left to right (starting at 1) to get the number of subpatterns.
</p>
<p>
When a back pattern is followed by a number for a replacement pattern (that is, the number immediately after a matching pattern), the familiar //1 symbol cannot be used to indicate a back reference.
For example, //11 will make preg_replace () unclear whether i want a back reference to //1 followed by a number 1 or a back reference to //11.
The workaround in this case is to use/${1} 1. This creates an isolated $1 back reference,And the other 1 is just plain text.
</p>
<p>
<strong>
Related examples of php regular expression replacement:
</strong>
</p>
<p>
Example 1. Back-reference usage followed by numbers
</p>
<div>
<pre>
<?php
$string="april 15, 2003";
$pattern="/(/w +) (/d +), (/d +)/i";
$replacement="/${1} 1,/$3";
print preg_replace ($pattern, $replacement, $string);
/* output
  ======
april1, 2003
* /
?>

If a match is found,The replaced subject will be returned, otherwise the original subject will be returned.

Each parameter (except limit) of preg_replace () can be an array.If both pattern and replacement are arrays,Processes in the order in which their keys appear in the array.This is not necessarily the same as the numerical order of the index.If you use an index to identify which pattern will be replaced by which replacement, you should sort the array with ksort () before calling preg_replace ().

Example 2. Using indexed arrays 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
  ======
the bear 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 subject is an array,Searches and replaces each item in the subject,And returns an array.

If both pattern and replacement are arrays,Preg_replace () will take the values ​​from it in order to search and replace the subject.If there are fewer values ​​in replacement than in pattern, the empty string is used as the remaining replacement value.If pattern is an array and replacement is a string,Use this string as the replacement value for each value in the pattern.The converse is meaningless.

The/e modifier causes preg_replace () to treat the replacement parameter as php code (after replacing the appropriate backreference). Tip:To ensure replacement constitutes a valid PHP code string,Otherwise php will report a parsing error in a line containing preg_replace ().

Example 3. 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}=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 capitalize all html tags in the input string,The above example supports the version of PHP 3>= 3.0.9, PHP 4.

Replace content with regex php

Used to do a project,Is a question and answer page,For example, insert expressions into the content of answers or questions.The name of the emoticon is written in the content (and without suffix,For example:f_002.png) emoji package is placed in the project,I need to replace the emoticon names with pictures when removing content.

The content stored in the database is this:I don't know [f_013] (the last [f_013] is the form in which the emoticons are stored in the database)

All I need to do is pull the content from the database,And treat characters like this in the content [f_013] into image addresses,Obviously regular expressions are needed here.

1. First I have to find this string

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

This regular match can help me find the expression string

2.When found, replace this string with the address where the emoticon image is stored.A function used here is the replacement of regular expressions.

This is the function:preg_match_all

echo preg_replace ("/(#face/\ ${1} .png ">", $line ["content"]);

$line ["content"] This is the content I took from the database,

"<img src =" __ public __/face/\ ${1} .png ">" This is the address of the image I will replace,For example, my picture address is like this:

There is a very important knowledge point:"\ ${1}" It is the character string stored in the database.

\ ${1}=f_013

I have a complete code I replaced here:

<?php
$result=array ();
   $n=preg_match_all ("/(?:\ [) (f _. [0-9] {1,3}) (?:\])/i", $line ["content"] , $result);/* Returns the number of found strings * /
   if ($n == 0 || $n == false)/* If it is 0 or false, there is no expression * /
{
    echo $line ["content"];
   } else
{
   echo preg_replace ("/(#face/\ ${1} .png ">", $line ["content"]);
   }
   ?>
  • Previous Takeown to get file or folder ownership
  • Next Detailed explanation of pointer structure array and pointer to structure variable in C ++