The specified character of the variable in php Regular Expression replacement

Source: Internet
Author: User
Tags php regular expression

The following three implementations are used to introduce the specified characters of variables in php Regular Expression replacement. For more information, see.

Three methods.

1.

The Code is as follows: Copy code

<? Php
$ Str = preg_quote ('(silver )');
$ Txt = 'My name (silver )';
Echo preg_replace ("/($ str)/", "<span style = 'color: # f00; '> $1 </span>", $ txt );
?>

2.

The Code is as follows: Copy code

<? Php
$ Str = quotemeta ('(silver )');
$ Txt = 'My name (silver )';
Echo preg_replace ("/($ str)/", "<span style = 'color: # f00; '> $1 </span>", $ txt );
?>

3.

The Code is as follows: Copy code
<? Php
$ Str = '(silver )';
$ Txt = 'My name (silver )';
Echo preg_replace ("/(Q $ strE)/", "<span style = 'color: # f00; '> $1 </span>", $ txt );
?>

All three methods return the same result. The Perl-style Regular Expression in PHP is exactly the same as that in Perl. quotemeta is also common ..


Some other regular expressions

Example:

The Code is as follows: Copy code

$ Text = "foobar123fooabcbar ";

$ Text = preg_replace ("/foo (? = Bar)/"," *** ", $ text );

// Match the position in front of bar *** bar123fooabcbar

 

The Code is as follows: Copy code

$ Text = "foobar123fooabcbar ";

$ Text = preg_replace ("/(? <= Bar) 123/"," *** ", $ text );

// Match the location foo behind the bar *** 123 fooabcbar

 

The Code is as follows: Copy code

$ Text = "foobar123fooabcbar ";

$ Text = preg_replace ("/foo (?! Bar)/"," *** ", $ text );

// Match the position behind the bar instead of foobar123 *** abcbar

 

The Code is as follows: Copy code

$ Text = "foobar123fooabcbar ";

$ Text = preg_replace ("/(? <! Foo) bar/"," *** ", $ text );

// Match foobar123fooabc, which is not the position of foo ***

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.