正規表達函式庫

ereg_replace

(PHP3 , PHP4)

ereg_replace ---  正規表達比對取代

語法 : string ereg_replace (string pattern, string replacement, string string)

說明 : 

此函式掃描string來和pattern比對,然後以replacement來取代比對到的文字

此函式傳回修改過的字串,如果比對不到則傳回原來的字串

如果pattern包含括弧的部份字串,則replacement可以包含" \\數字"的部份字串,這將會以第幾個括弧內的部份字串來替代。\\0將會產生整個字串的內容,最多可使用到九個部份字串,這種情況下它會以開啟的括弧來計算

如果在string中找不到比對則將會傳回未改變的字串string

以下的範例會將字串切斷,並顯示三次 "This was a test" :

<?php

    $string = "This is a test"; 

    echo ereg_replace (" is", " was", $string); 

    echo ereg_replace ("( )is", "\\1was", $string); 

    echo ereg_replace ("(( )is)", "\\2was", $string);

?>

有一個地方需要去注意的是,如果你在參數replacement中使用整數值的時候,你可能無法取得到結果,這是因為ereg_replace( )將會把數字解釋成字元的順序(ordinal)值,並且執行它,例如 :

<?php

   /* This will not work as expected. */ 

  $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( )  eregi( )  eregi_replace( )


上一頁 首頁 下一頁