萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php 正則 ereg_replace替換

php 正則 ereg_replace替換

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>

copyright © 萬盛學電腦網 all rights reserved