本文實例講述了PHP正則表達式函數preg_replace用法。分享給大家供大家參考,具體如下:
preg_replace 執行一個正則表達式的搜索和替換
語法:preg_replace (pattern ,replacement ,subject,limit,count )
參數 | 描述 |
---|---|
pattern | 正則表達式(字符串或字符串數組) |
replacement | 用于替換的字符串或字符串數組 |
subject | 要進行搜索和替換的字符串或字符串數組。 |
limit | 可選。每個模式在每個subject上進行替換的最大次數。默認是 -1(無限)。 |
count | 可選。完成的替換次數 |
Example 1
1
2
3
4
5
|
$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
1
2
3
4
|
$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
1
2
3
|
$str = 'nice !' ; $str = preg_replace( '/\s+/' , '' , $str ); echo $str ; |
結果:
nice!
Example 4
1
2
3
|
$count = 0; echo preg_replace( array ( '/\d/' , '/[a-z]/' ), '*' , 'xp 4 to' , -1, $count ); echo $count ; |
結果:
** * **5
希望本文所述對大家PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/huangyuxin_/article/details/79660162