Get invalid date and preg_replace it

I have this to replace the valid date:

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

So, these dates: 08/25/2016 will be replaced.

My problem: sometimes users write dates like this:

082/5/2016
0825/2016
08/252/016
08/25/201
0/85/2016

I want to get this as well. Any ideas?

+4
source share
2 answers

If you have “strings such as dates” in your input, you can use a regular expression with a positive lookbehind to make sure the digits and slashes contain 7 to 8 digits, and then follow with word boundaries:

'~\b(?=(?:\D*\d){7,8}\b)\d+(?:/\d+)+\b~'

See the demo version of regex .

More details

  • \b - word boundary
  • (?=(?:\D*\d){7,8}\b) - , , 7 8 ,
  • \d+ - 1
  • (?:/\d+)+ - 1 / + 1
  • \b - .

- PHP:

$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;
+2

strtotime, .

$array = array('082/5/2016', '0825/2016', '08/252/016', '08/25/201', '0/85/2016', '08/25/2016');
foreach($array as $key => $date) {
     if(!strtotime($date)) {
         unset($array[$key]); //or handle the invalid date however you want
     }
}
print_r($array);

: https://eval.in/628649

+2

Source: https://habr.com/ru/post/1652458/


All Articles