php ereg_replace — 替換Regex

來源:互聯網
上載者:User
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);
?>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.