第一种方法,代码如下:
- <?php
- $str = preg_quote('(银子)');
- $txt = '我的呢称(银子)';
- echo preg_replace("/($str)/","<span style='color:#f00;'>$1</span>",$txt);
- ?>
第二种方法,代码如下:
- <?php
- $str = quotemeta('(银子)');
- $txt = '我的呢称(银子)';
- echo preg_replace("/($str)/","<span style='color:#f00;'>$1</span>",$txt);
- ?>
第三种方法,代码如下:
- <?php
- $str = '(银子)';
- $txt = '我的呢称(银子)';
- echo preg_replace("/(Q$strE)/","<span style='color:#f00;'>$1</span>",$txt);
- ?>
三种方法都返回同样结果.. PHP中的Perl风格正则与Perl完全一样.连quotemeta也是通用的..
一些其它关于正则的实例,代码如下:
- $text = “foobar123fooabcbar”;
- $text = preg_replace(“/foo(?=bar)/”, “***”, $text);
-
-
- $text = “foobar123fooabcbar”;
- $text = preg_replace(“/(?<=bar)123/”, “***”, $text);
-
-
- $text = “foobar123fooabcbar”;
- $text = preg_replace(“/foo(?!bar)/”, “***”, $text);
-
-
- $text = “foobar123fooabcbar”;
- $text = preg_replace(“/(?<!foo)bar/”, “***”, $text);
-