Search code examples
phpdateuser-inputdate-formatting

How to conditionally reformat user input if a date string of dd/mm/yyyy to yyyy-mm-dd?


I've added Search functionality in my form. When a user enters date 18/03/2015 then I want to reformat the date. I need to change $_GET['searchKeyword'] from '18/03/2015' to '2015-03-18' and save as $searchKeyword.

I want this for my sql LIKE clause. I write like this, but it is not working:

$where_clause = ''; 
$searchKeyword =  $_GET['search_keyword'];

if ($_GET['search_keyword'] != '')
{   
    if (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $_GET['searchKeyword'], $m)) 
    {
        $searchKeyword = "$m[3]-$m[2]-$m[1]";
        $where_clause = " where patient_id  like '%" .$searchKeyword . "%'
                          or patient_name like '%" .$searchKeyword . "%'
                          or in_date like '%" . $searchKeyword . "%'
                          or discharge_date like '%" . $searchKeyword ."%'";    
    } else {
        $where_clause = " where patient_id  like '%" .$searchKeyword . "%'
                          or patient_name like '%" .$searchKeyword . "%'
                          or in_date like '%" . $searchKeyword . "%'
                          or discharge_date like '%" . $searchKeyword . "%'";
    }
}

Solution

  • Let's break it down into 2 parts:

    (1) Find out if it matches the pattern

    if (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $_GET['searchKeyword'], $m)) {
    

    (2) Assign to your variable

        $searchKeyword = "$m[3]-$m[2]-$m[1]";
    }
    

    The regex above "captured" 3 different groups (the part in parens) which are then available as $m[1], $m[2], and $m[3], respectively. You can swap them around and format them as you wish.