ereg_replace -- 正則表達式替換(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);
首先這個正則表達式匹配 類似格式:
<td*title*>*</td>,這里每個星號*代表的是多個任意字符,相當于每個*對應正則里的[^<>]+,為了匹配準確,這里任意字符里不包含'<','>'.
對于第二種里的替換字符串$1和$2,分別為正則表達式里對應的兩組()內匹配的值.這種形式正則里叫 子模式匹配.$1和$2叫反向匹配的結果.
這里$1匹配的結果是<td class='title'>,$2匹配的結果是</td>.
新聞熱點
疑難解答