網上一段簡單的preg_match替換 不明
$string = "Is is the cost of of gasoline going up up";
$pattern = "/\b([a-z]+) \\1\b/i";
if(preg_match($pattern, $string,$arr)){
print_r($arr);
echo preg_replace($pattern, '$1', $string);
}
輸出
Array
(
[0] => Is is
[1] => Is
)
Is the cost of gasoline going up
我理解的preg_match($pattern,$repalce,$subject)是用pattern從subject匹配到各個分組,然後用replace規定的顯示方式,重新輸出
$pattern = "/\b([a-z]+) \\1\b/i" 匹配到的只有Is is 和Is
重新輸出怎麼會輸出一整句話 Is the cost of gasoline going up
還有什麼時候用$1 什麼時候用\\1 擷取子模式比對的內容 在雙引號和單引號裡又有什麼要求? php?正則
分享到:
------解決方案--------------------
preg_match 匹配一次,
而
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
第三個參數未指定時,預設是 -1(無限)。
$1 與 \1 的區別:
\1 可以同時使用在模式和替換字串中
$1 只能用於替換字串中
------解決方案--------------------
preg_match只匹配第一個符合的,要全部匹配要用preg_match_all
replace是符合的都替換(符合的部分與preg_match_all相同)
$與\只是習慣問題,一般同一個正則內用\,\的寫法較接近perl
單雙引號注意原文\\這種情況就基本可以了,其他的無歧義就按原文
------解決方案--------------------
$pattern="
------解決方案--------------------
<[^>]+>(.*)]+>
------解決方案--------------------
";
$pattern="/<[^>]+>(.*)<\/[^>]+>/";
是一樣的
如果分界符是 / ,那麼規則串中的 / 就需要轉義
幸好 php 提供了自訂分界符,可以使規則串看起來舒服點
要是 js 的話,就沒有那麼幸運了