網上一段簡略的preg_match替換 不明

來源:互聯網
上載者:User
網上一段簡單的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 的話,就沒有那麼幸運了
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.