php 正則 ereg_replace替換

來源:互聯網
上載者:User

ereg_replace -- Regex替換(php教程 3, php 4, php 5)

string ereg_replace ( string pattern, string replacement, string string )

本函數在 string 中掃描與 pattern 匹配的部分,並將其替換為 replacement。

返回替換後的字串。(如果沒有可供替換的匹配項則會返回原字串。)


<?php
$string = "this is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "1was", $string);
echo ereg_replace("(( )is)", "2was", $string);
?>

輸出如下:
that was a test
that was a test
that was a test


<td class='title'>熱賣oou限量版雙人浴巾</td>
整個替換為空白,還是將
<td class='title'>熱賣oou限量版雙人浴巾</td>
替換成
<td class='title'></td>

第一種

echo preg_replace('/(<td[^<>]+title[^<>]+>)[^<>]*(</td>)/i', '', $html);


第二種:

echo preg_replace('/(<td[^<>]+title[^<>]+>)[^<>]*(</td>)/i', '$1$2', $html);


首先這個Regex匹配 類似格式:
<td*title*>*</td>,這裡每個星號*代表的是多個任一字元,相當於每個*對應正則裡的[^<>]+,為了匹配準確,這裡任一字元裡不包含'<','>'.
對於第二種裡的替換字串$1和$2,分別為Regex裡對應的兩組()內匹配的值.這種形式正則裡叫 子模式比對.$1和$2叫反向匹配的結果.

這裡$1匹配的結果是<td class='title'>,$2匹配的結果是</td>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.