Php uses preg_replace to implement regular expression search results and replace corresponding array key values

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

1. Usage and usage of preg_replace

Purpose: Search and replace regular expressions;

Regular expression replacement

The preg_replace () function is used to search and replace regular expressions.

Syntax:

Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])

Example

1. Reverse reference followed by numbers

The code is as follows: Copy code

<? Php
$ String = "April 15,200 3 ";
$ Pattern = "/(/w +) (/d +), (/d +)/I ";
$ Replacement = "/$ {1} 1,/$3 ";
Print preg_replace ($ pattern, $ replacement, $ string );

/* Output
======

April1, 2003

*/
?>


2. Match and replace the key value of the array

PHP regular expression modifier e.

E (PREG_REPLACE_EVAL): If this modifier is set, preg_replace () after replacing the string with a reference, the replaced string is evaluated and executed as the php code (eval function mode), and the execution result is used as the string to be replaced. Single quotation marks, double quotation marks, backslash (), and NULL characters are escaped by backslash when being replaced by a forward reference.

Example:

The code is as follows: Copy code


$ User_data = array ('User _ id' => 2, 'username' => 'Mr. Zhang ');
$ Words = 'Hello, <A href = "profile # {$ user_id}" >{$ username} </A> ';
$ Hello = preg_replace ('/{$ ([w] +)}/E', "$ user-> data [' $ {1} ']", $ words );

Echo $ hello;

// The output result is similar to: Hello, <A href = "profile #2"> Mr. Zhang </A>

The above is to replace the search result of the regular expression with the key value corresponding to the array.

You can also process these search results.

 

The code is as follows: Copy code
$ Text = "Hello, phper ";
$ Encoded = preg_replace (
"'(.) 'E"
, "Dechex (ord ('\ 1 '))"
, $ Text
);
Print "ENCODED: $ encodedn ";

The example uses the index array in preg_replace ().

The code is as follows: Copy code

<? 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 shoshould 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 an array, it searches and replaces each item in the subject and returns an array.

If both pattern and replacement are arrays, preg_replace () extracts values from them to search and replace subject. If the value in replacement is less than that in pattern, an 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. In turn, it makes no sense.

The/e modifier enables preg_replace () to treat the replacement parameter as PHP code (after appropriate reverse references are replaced ). Tip: Make sure that the replacement constitutes a valid PHP code string. Otherwise, PHP will report a syntax parsing error in the row containing preg_replace.


Only once

Such as the question, there is a piece of text
123456 <a href = ""> abcdefg </a> sdfsdafdfabcdffsafd

Purpose: replace the abc that appears for the second time.

The code is as follows: Copy code

$ Test = 'Test test1 ';
$ Arr [0] = '/(test )/';
$ Arr [1] = '/(yjq )/';
$ Val [0] = 'yjq ';
$ Val [1] = 'test ';
$ Test1 = preg_replace ($ arr [0], $ val [0], $ test );
$ Test1 = preg_replace ($ arr [1], $ val [1], $ test1, 1 );
Echo $ test. ':'. $ test1;

You can also use the preg_replace function to operate on this professional mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit]). We only need to limit the limit to the limit parameter.

The code is as follows: Copy code

<?
Function str_replace_limit ($ search, $ replace, $ subject, $ limit =-1 ){

// Constructing mask (s )...

If (is_array ($ search )){

Foreach ($ search as $ k => $ v ){

$ Search [$ k] = '''. preg_quote ($ search [$ k], '''). ''';

}

}

Else {

$ Search = '''. preg_quote ($ search ,''').''';

}

// Replacement

Return preg_replace ($ search, $ replace, $ subject, $ limit );

}

?>

A more direct

<? Php
Function sst ($ result, $ keys ){
$ Len = substr_count ($ result, $ keys );
For ($ I = 1; $ I <= $ len; $ I ++ ){
$ Num = $ I .",";
$ Result = preg_replace ("/$ keys/", $ num, $ result, 1 );
Echo $ result. "<br/> ";
  }

Return $ result;
 }

Sst ("<xdw> occurrence of <xdw> 123544 +; <xdw> 545", "<xdw> ");

?>


 

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.