PHP正則表達式函數preg_replace用法實例分析
本文實例講述了PHP正則表達式函數preg_replace用法。分享給大家供大家參考,具體如下:
preg_replace 執行一個正則表達式的搜索和替換
語法:preg_replace (pattern ,replacement ,subject,limit,count )
參數 描述 pattern 正則表達式(字符串或字符串數組) replacement 用于替換的字符串或字符串數組 subject 要進行搜索和替換的字符串或字符串數組。 limit 可選。每個模式在每個subject上進行替換的最大次數。默認是 -1(無限)。 count 可選。完成的替換次數
Example 1
$string = ’huang yu xin’;$pattern = ’/(w+) (w+) (w+)/i’;$replacement = ’${1}a $3’;// $1對應(w+),${1}a是區別$1a,說明是$1和a不是$1a,$3對應第三個(w+)echo preg_replace($pattern, $replacement, $string);
結果是:
huanga xin
Example 2
$string = 'nice to meet you';$pattern = array();$replace = array();echo preg_replace(array(’/nice/’, ’/you/’), array(’Nice’, ’me’), $string);
結果:
Nice to meet me
Example 3
$str = ’nice !’;$str = preg_replace(’/s+/’, ’’, $str);echo $str;
結果:
nice!
Example 4
$count = 0;echo preg_replace(array(’/d/’, ’/[a-z]/’), ’*’, ’xp 4 to’, -1, $count);echo $count;
結果:
** * **5
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:http://tools.jb51.net/regex/create_reg
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php正則表達式用法總結》、《php程序設計安全教程》、《php安全過濾技巧總結》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php字符串(string)用法總結》及《php+mysql數據庫操作入門教程》
希望本文所述對大家PHP程序設計有所幫助。
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析3. SharePoint Server 2019新特性介紹4. ASP中常用的22個FSO文件操作函數整理5. 三個不常見的 HTML5 實用新特性簡介6. ASP調用WebService轉化成JSON數據,附json.min.asp7. .Net core 的熱插拔機制的深入探索及卸載問題求救指南8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. 讀大數據量的XML文件的讀取問題10. 解決ASP中http狀態跳轉返回錯誤頁的問題
