Search code examples
phpregexpreg-match

PHP finding month and year from a string?


This is what I have tried so far getting year from any type of string.

<?php

  $variable = [
      'Well year is 1967 month jan',
      'year is 1876 but month January',
      'HOLLA April Evening 2017',
      'DOLLA-May 2020',
      'OH-YESApril 2019 (IGNORE)',
      'Just a sample String without year ok lets just add 1'
  ];
  foreach ($variable as $value) {
      if(ContainsNumbers($value)){
           $input = preg_replace('/^[^\d]*(\d{4}).*$/', '\1', $value);
            $input = (int)$input;
                if($input>1000 && $input<2100)
                {
                   var_dump($input);
                }                   
      } 
  }
  function ContainsNumbers($String){
    return preg_match('/\\d/', $String) > 0;
}
?>

Here is an output of above code

int(1967)
int(1876)
int(2017)
int(2020)
int(2019)

The only thing I want now is getting month from the string . For month I am getting help from this link but no luck so far :- I don't know what to add in $data

$str = 'December 2012 Name: Jack Brown';
$ptr = "/^(?P<month>:Jan(?:uary)?|Feb(?:ruary)?|Dec(?:ember)?) (?P<year>:19[7-9]\d|2\d{3}) (Name:(?P<name>(.*)))/";
 var_dumb(preg_match($ptr, $str, $data););

Here is a play ground


Solution

  • Traditionally, almost everyone calls the third parameter to preg_match $matches, so I'm going to go with the nomenclature here.

    If the RegEx matches, the third parameter will be an array with numeric indexes for each items, as well named-indexes if you have any named matches. So you are looking for:

    if(preg_match($ptr, $str, $matches)){
        var_dump($matches);
    }
    

    Which will give you:

    Array
    (
        [0] => December 2012 Name: Jack Brown
        [month] => December
        [1] => December
        [year] => 2012
        [2] => 2012
        [3] => Name: Jack Brown
        [name] =>  Jack Brown
        [4] =>  Jack Brown
        [5] =>  Jack Brown
    )