2010-07-23 77 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);