这里介绍三种常用方法.
方法一:
<?php $str = preg_quote('(银子)'); $txt = '我的呢称(银子)'; echo preg_replace("/($str)/","<span>$1</span>",$txt); ?>
方法二:
<?php $str = quotemeta('(银子)'); $txt = '我的呢称(银子)'; echo preg_replace("/($str)/","<span>$1</span>",$txt); ?>
方法三:
<?php $str = '(银子)'; $txt = '我的呢称(银子)'; echo preg_replace("/(Q$strE)/","<span>$1</span>",$txt); ?>
三种方法都返回同样结果.. PHP中的Perl风格正则与Perl完全一样.连quotemeta也是通用的..
一些其它关于正则的实例
例子:
$text = "foobar123fooabcbar"; $text = preg_replace("/foo(?=bar)/", "***", $text); //匹配bar前面的位置 ***bar123fooabcbar
$text = "foobar123fooabcbar"; $text = preg_replace("/(?<=bar)123/", "***", $text); //匹配bar后面的位置 foo***123fooabcbar
$text = "foobar123fooabcbar"; $text = preg_replace("/foo(?!bar)/", "***", $text); //匹配后面跟的不是bar的位置 foobar123***abcbar
$text = "foobar123fooabcbar"; $text = preg_replace("/(?<!foo)bar/", "***", $text); //匹配前面不是foo的位置 foobar123fooabc***