ereg_replace -- 替換Regex
說明
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); ?> |
|