php正則替換變量中的指定字符
來源:程序員人生 發布時間:2014-06-12 05:34:31 閱讀次數:2431次
第一種方法,代碼如下:
- <?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);
-
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈