//string ereg_replace ( string $pattern , string $replacement , string $string )
/*
修改後的字串返回。如果沒有找到匹配的字串,那麼將返回不變
*/
//執行個體
| 代碼如下 |
複製代碼 |
$string = "this 111cn.net a test"; echo str_replace(" 111cn.net", " was", $string); echo ereg_replace("( )111cn.net", "\1was", $string); echo ereg_replace("(( )111cn.net)", "\2was", $string); |
/*
有一點要注意的是,如果你使用一個整數參數值作為替代,您可能不會得到你期望的結果。這是因為ereg_replace()將解釋為一個字元值序數,並套用。例如
*/
| 代碼如下 |
複製代碼 |
| $num = 4; $string = "this string has four words."; $string = ereg_replace('four', $num, $string); echo $string; /* output: 'this string has words.' */ /* this will work. */ $num = '4'; $string = "this string has four words."; $string = ereg_replace('four', $num, $string); echo $string; /* output: 'this string has 4 words.' */ |
//來看一個用ereg_replace擷取串連代碼
| 代碼如下 |
複製代碼 |
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href="\0">\0</a>", $text); |
//取字串中一部份
| 代碼如下 |
複製代碼 |
$output = ereg_replace("your regexp here", "<font color=red>\0</font>", $input) ; print $output; |
//再來看一個更複雜的執行個體
| 代碼如下 |
複製代碼 |
function strip_urls($text, $reppat) { if(!$reppat){ $reppat = "text [url]"; } $aimps教程tr = 'php教程_strip_urls_function_by_real-php-geek'; //change $aimps教程tr to anything you want. $impstr = md5($aimpstr); $text = str_replace('</a>', '</a>' . $impstr, $text); $text = explode($impstr, $text); $n = 0; $texta = array(); $reppat = str_ireplace(array('text', 'url'), array('\4', '\2'), $reppat); foreach ($text as $text) { $texta[$n] = ereg_replace("<a(.*)href="(.*)"(.*)>(.*)</a>", $reppat, $text); $n++; } $textb = implode("</a>", $texta); return $textb; } |
//examples:
| 代碼如下 |
複製代碼 |
$string_of_text = '<a href="http://www.111cn.net/">php</a> rocks. <a href="http://www.111cn.net/">網頁製作教程教程</a> also!'; echo strip_urls($string_of_text, "text"); echo strip_urls($string_of_text, "url"); echo strip_urls($string_of_text, "text [url]"); echo strip_urls($string_of_text, null); |
/*
說明:
在 subject 中搜尋 pattern 模式的匹配項並替換為 replacement。如果指定了 limit,則僅替換 limit 個匹配,如果省略 limit 或者其值為 -1,則所有的匹配項都會被替換。
replacement 可以包含 \n 形式或(自 php 4.0.4 起)$n 形式的逆向引用,首選使用後者。每個此種引用將被替換為與第 n 個被捕獲的括弧內的子模式所匹配的文本。n 可以從 0 到 99,其中 \0 或 $0 指的是被整個模式所匹配的文本。對左圓括弧從左至右計數(從 1 開始)以取得子模式的數目。
對替換模式在一個逆向引用後面緊接著一個數字時(即:緊接在一個匹配的模式後面的數字),不能使用熟悉的 \1 符號來表示逆向引用。舉例說 \11,將會使 preg_replace() 搞不清楚是想要一個 \1 的逆向引用後面跟著一個數字 1 還是一個 \11 的逆向引用。本例中的解決方案是使用 ${1}1。這會形成一個隔離的 $1 逆向引用,而使另一個 1 只是單純的文字。
*/