PHP中 preg_replace()函數的使用


定義

preg_replace — 正則表達式匹配替換

用法

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

搜索subject中符合pattern的部分,並用replacement替代。
replacement和pattern均可以是數組。
使用比較簡單,功能和用法均類似於 str_replace.
比較難理解的是 replacement 可以后向引用。

replacement may contain references of the form \n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. Note that backslashes in string literals may require to be escaped.

示例

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
// \1=April \2=15 \3=2003  \均可用$代替
preg_replace($pattern, $replacement, $string);
//April1,2003

其中,雙引號中 \ 和 $ 均需要轉義,單引號不用,下面這幾個是等價的

'${1}1,$3' == “\${1}1,\$3” == “\${1}1,\\3”

所以為了書寫簡潔,便於閱讀,推薦全部使用單引號。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM