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 ***