Skip to content
Advertisement

Validate if the string contains year, month, day?

I am working on a search field. User can write anything on search bar. If I search by typing only October, I need only October. If search is October 2020, it should return month & year.

How can I validate if the string used is only month or year or day ?

        $dateValue = strtotime($searchString);

        $year = date("Y", $dateValue);
        $month = date("m", $dateValue);
        $day = date("d", $dateValue);

Advertisement

Answer

This checking is working but not perfect

  var_dump(searchDate("October")); //string(7) "October"
  var_dump(searchDate("20 2021 Jan")); //string(15) "January 20 2021"
  var_dump(searchDate("February 2020 2")); //string(16) "February 02 2020"
  var_dump(searchDate("October 20")); //string(10) "October 20"
  var_dump(searchDate("DeC 2020")); //string(13) "December 2020"
  var_dump(searchDate("2020 Sept ")); //string(14) "September 2020"
  var_dump(searchDate("2020 Nov 1")); //string(16) "November 01 2020"
  var_dump(searchDate("2020 Apr")); //string(10) "April 2020"
  var_dump(searchDate("jUnE 12,2020")); //string(10) "June 12 2020"
  var_dump(searchDate("2020 March 12")); //string(13) "March 12 2020"
  var_dump(searchDate("2020")); //string(5) "2020"
  var_dump(searchDate("12")); //string(3) "12"
  var_dump(searchDate("Jan 30 2020")); //string(15) "January 30 2020"
 
  function searchDate($search,$calendar = CAL_GREGORIAN) {

    $date = array();

    $months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ];

    foreach($months as $month) {

      $alpha = preg_replace("/[^a-zA-Z]+/", "", $search);

      if(false !== stripos($month,$alpha)) {

        $date['month'] = $month;

      }

    }

    if(preg_match_all('!d+!', $search, $matches)) {
      $date['numeric'] = $matches[0];
    }

    if(isset($date['numeric'])) {

      foreach($date['numeric'] as $d) {
        
        if(strlen($d) == 4) {
          
          if( false !== (strtotime($d) )) $date['year'] = $d;
          else $date['year'] = false;
          
        }
        
        if(strlen($d) <= 2 ) {

          if($d >= 1) {
            $date['day'] = $d < 10 ? "0{$d}" : $d;
          }

        }

      }

    unset($date['numeric']);

    }

    if(isset( $date['year'] ) && isset($date['month']) ) {
      $len = cal_days_in_month($calendar,date_parse($date['month'])['month'], $date['year']);

      if(isset($date['day']) && $date['day'] > $len) unset($date['day']);
    }

    $join = '';

    if(isset($date['month']))
      $join .= $date['month'];
    if(isset($date['day']))
      $join .= " {$date['day']}";
    if(isset($date['year']))
      $join .= " {$date['year']}";

    return trim($join);
  }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement