Reputation: 832
I am trying to remove all dates from strings in PHP using preg_replace(). The dates are of the following formats: YYYY-MM-DD, YYYY/MM/DD or 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);
Expected output is "Current from to ". Currently I am getting back "".
Any help greatly appreciated! Wonko
Upvotes: 2
Views: 3159
Reputation: 833
This should work.
$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;
Update To ensure that the date also is valid
<?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;
Upvotes: 3