在PHP中从字符串中删除日期

时间:2015-06-01 23:58:58

标签: php date preg-replace

我正在尝试使用preg_replace()从PHP中删除字符串中的所有日期。日期格式如下:YYYY-MM-DD,YYYY / MM / DD或YYYY.MM.DD

$string1 = "Current from 2014-10-10 to 2015-05-23";    
$output = preg_replace('/\d{4}[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])/g', '', $string1);      

预期输出为"当前为"。目前我正在回来""。

任何帮助非常感谢! Wonko

1 个答案:

答案 0 :(得分:2)

这应该有用。

$input = "Current from 2014-10-10 to 2015/05/23 and 2001.02.10";
$output = preg_replace('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', '', $input);
echo $output;

<强>更新 确保日期也有效

<?php
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.19.10";
$output = preg_replace_callback('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', function($matches) {
    $date = str_replace(array('.','/'), '-', $matches[1]);
    $newDate = DateTime::createFromFormat('Y-m-d', $date);
    if($newDate->format('Y-m-d') == $date) {
        return false;
    }else {
        return $matches[1];
    }
}, $input);
echo $output;