定義
preg_replace — 正則運算式匹配替換
用法
preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed
搜索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.
下面舉個例子,說明下
示例
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
// \1=April \2=15 \3=2003 \均可用$代替
echo preg_replace($pattern, $replacement, $string);
?>
April1,2003
其中,雙引號中 \ 和 $ 均需要轉義,單引號不用,下面這幾個是等價的
'${1}1,$3' == “\${1}1,\$3” == “\${1}1,\\3”
所以為了書寫簡潔,便于閱讀,推薦全部使用單引號,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/55083.html
標籤:PHP
