Abhranil Majumder Abhranil Majumder - 7 months ago 22
PHP Question

PHP Regex for 12 Jan 2016

Please tell the regex code to find all the dates in the string using php, in the format listed below :

12 Jan 2016


Suppose the string is

Test Test 12 Jan 2016 Its Testing 18 Feb 2018, test 21 Aug 2013.

I need all the three dates in Y-m-d format

Answer

The solution using preg_match_all, array_walk and strtotime functions:

$str = "Test Test 12 Jan 2016 Its Testing 18 Feb 2018, test 21 Aug 2013.";
preg_match_all("/\d{2} [A-S][a-z]{2} [12][0-9]{3}/", $str, $matches);
array_walk($matches[0], function(&$v){
    $v = date('Y-m-d', strtotime($v));    
});

print_r($matches[0]);

The output:

Array
(
    [0] => 2016-01-12
    [1] => 2018-02-18
    [2] => 2013-08-21
)

The additional solution for another date format (7 JAN 16 19:32 PM):

$str = "Swensen s AMK Hub 53 Ang Mo Kio Ave 3 TEL : 6481 4316 FAX : 6481 6734 Company Reg. N GST No. 51384001 Mandy CHK 30625 TBL. GST 1 7 JAN 16 19:32 PM D i ne In 1 Salm Mush Pasta 16.20 1 Crayfish Pasta 17.90 1 Creamy Mushroom 9.80 Subtotal $43.90 Service Charge $4.39 7% GST $3.38 Payment $51.67 Change Due o. oo Master $51.67 6575 ......... Check Closed......-...... 7 JAN 16 20:22 PM Home Delivery of ice cream cakes available now. Call 6481 4316 Thank You & Please Come Again 4 Signature: ";

preg_match_all("/\d{1,2} [A-Z]{3} \d{2,4} \d{2}:\d{2} (AM|PM)/", $str, $matches);
array_walk($matches[0], function(&$v){
    $v = str_replace([" PM", " AM"], ["P.M.", "A.M."], $v);
    $v = date('Y-m-d', strtotime($v));    
});

print_r($matches[0]);

The output:

Array
(
    [0] => 2016-01-07
    [1] => 2016-01-08  // depends on your locale
)
Comments