ereg_replace

(PHP 3, PHP 4, PHP 5)

ereg_replace -- 置換正則表達式

說明

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

本函數在 string 中掃瞄與 pattern 符合的部分,並將其置換為 replacement

返回置換後的字串。(若果沒有可供置換的符合項則會返回原字串。)

若果 pattern 包括有括號內的子串,則 replacement 可以包括形如 \\digit 的子串,這些子串將被置換為數字表示的的第幾個括號內的子串;\\0 則包括了字串的整個內容。最多可以用九個子串。括號可以嵌套,此情形下以左圓括號來計算順序。

若果未在 string 中找到符合項,則 string 將原樣返回。

例如,下面的代碼片斷輸出 "This was a test" 三次:

例子 1. ereg_replace() 例子

<?php

$string 
"This is a test";
echo 
str_replace(" is"" was"$string);
echo 
ereg_replace("( )is""\\1was"$string);
echo 
ereg_replace("(( )is)""\\2was"$string);

?>

要注意的一點事若果在 replacement 參數中使用了整數值,則可能得不到所期望的結果。這是因為 ereg_replace() 將把數字作為字元的序列值來解釋並套用之。例如:

例子 2. ereg_replace() 例子

<?php
/* 不能產生出期望的結果 */
$num 4;
$string "This string has four words.";
$string ereg_replace('four'$num$string);
echo 
$string;   /* Output: 'This string has   words.' */

/* 本例工作標準 */
$num '4';
$string "This string has four words.";
$string ereg_replace('four'$num$string);
echo 
$string;   /* Output: 'This string has 4 words.' */
?>

例子 3. 將 URL 置換為超連線

<?php
$text 
ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     
"<a href=\"\\0\">\\0</a>"$text);
?>

提示: preg_replace() 函數使用了 Perl 相容正則表達式語法,通常是比 ereg_replace() 更快的替代專案。

參見 ereg()eregi()eregi_replace()str_replace()preg_match()