1. 程式人生 > 程式設計 >PHP正則表示式函式preg_replace用法例項分析

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程式設計有所幫助。