Rick Joe Rick Joe - 10 months ago 70
PHP Question

get invalid date and preg_replace it

I have this to replace valid date:

$date = preg_replace('~(\d{2})/(\d{2})/(\d{2,4})~', '', $date);

So dates like this: 08/25/2016 will be replaced.

My problem is, sometimes users write dates like this:


I want to be able to get this too. Any ideas?


In case you have "strings like dates" in your input, you may use a regex with a positive lookbehind to make sure the digits and forward slashes chunk contains 7 to 8 digits and then followed with a word boundary:


See regex demo.


  • \b - leading word boundary
  • (?=(?:\D*\d){7,8}\b) - a lookahead requiring that the word boundary is followed with 7 to 8 digits separated with any amount of non-digits
  • \d+ - 1 or more digits
  • (?:/\d+)+ - 1 or more sequences of / + 1 or more digits
  • \b - trailing word boundary.

PHP demo:

$str = "Text containing \n082/5/2016\n0825/2016\n08/252/016\n08/25/201\n0/85/2016\n08/25/2016"; 
$result = preg_replace('~\b(?=(?:\D*\d){7,8})\d+(?:/\d+)+\b~', "", $str);
echo $result;