tags:

views:

79

answers:

5

How do I check with preg_match if string contains year which is between 1950 and 2010 ?

example:

$string = "I was born in 1986 year.";

+6  A: 

Assuming you have a timestamp:

$date = getdate($timestamp);
if ($date['year'] >= 1950 && $date['year'] <= 2010)
  return 'good';
cambraca
and if you dont have a timestamp you get one with `strtotime` or use `date_parse`
Gordon
for regular number is => ([0-9]{1,})
somewhereInPHP
A: 
$date = getdate( $timestamp );
if( (int)$date['year'] >= 1950 && (int)$date['year'] <= date('Y') ) {
   return 'good';
}

:P

if( preg_match( '/^(19[5-9]{1}[0-9]{1}|20(0[0-9]{1}|10))$/', $i ) ) {}
// tested - works. 1950-2010
Tobias
A: 

for regular number is => ([0-9]{1,})

somewhereInPHP
+3  A: 

If the string is already formatted in a way that can be consumed by getdate(), the other answers would be the best solution.

If the string is just some random text which might or might not contain a date, you'd need to use a regex to find those numbers.

/(19[5-9][0-9]|20(0[0-9]|10))/

Of course, you have no guarantee that the numbers matched this way is actually a year. It could be 2005 pounds of steel or 1976 miles of highway.

kijin
+1 for regex and issues with using a regex...
ircmaxell
ah right - i can leave the {1} away... well.. ;)
Tobias
A: 

It's not ok like that: 19[5-9]{1}[0-9]{1}|20(0[0-9]{1}|10)

Why?

Because I get current year from date('Y'): $current_year = date('Y'); $current_work_year = substr($current_year, -2);

19[5-9]{1}[0-9]{1}|20(0[0-9]{1}|$current_work_year)

somewhereInPHP
well he wasn't asking for the current year. he was asking for 1950-2010.
Tobias
btw. check the manual - for the next 9 years you can use: if( preg_match( '/^(19[5-9][0-9]|20(0[0-9]|'.date('y').'))$/', $year ) ) {}
Tobias