第一種方法,代碼如下:
- <?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);
- //匹配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***
新聞熱點
疑難解答