Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEXR help - how to extract a year from a string

Tags:

regex

php

I have a year listed in my string

$s = "Acquired by the University in 1988";

In practice, that could be anywhere in this single line string. How do I extract it using regexr? I tried \d and that didn't work, it just came up with an error.

Jason

I'm using preg_match in LAMP 5.2

like image 370
Jason Avatar asked Nov 29 '22 16:11

Jason


1 Answers

You need a regex to match four digits, and these four digits must comprise a whole word (i.e. a string of 10 digits contains four digits but is not a year.) Thus, the regex needs to include word boundaries like so:

if (preg_match('/\b\d{4}\b/', $s, $matches)) {
    $year = $matches[0];
}
like image 164
ridgerunner Avatar answered Dec 06 '22 09:12

ridgerunner