2010-07-23 76 views
0

所以我試圖創建這個函數,它用別的東西代替某個符號。我打算使用ereg_replace,但我看到它在5.3中已被棄用。你們可以給我一些關於如何使用這個目的的建議。php ereg_replace in php 5.3

爲了更具體一些,我想創建一個函數,解析一個電子郵件,用當前日期替換電子郵件中的某個符號。

<date-1> 

將是昨天的日期和

<date> 

將是今天的日期。

謝謝!

回答

7

改爲使用preg_replace()。此頁面突出了差異:http://php.net/manual/en/reference.pcre.pattern.posix.php

至於你的具體問題,這應該這樣做:

$string = 'test <date> test2 <date-1> test3 <date+3>'; 

echo preg_replace_callback('#<date(?:([+-])(\d+))?>#', function($match) { 
    if (!isset($match[1])) { 
     return date('Y-m-d'); 
    } 
    return date('Y-m-d', strtotime(sprintf('%s%d days', $match[1], $match[2]))); 
}, $string);