Jason Jason - 3 months ago 15
PHP Question

REGEXR help - how to extract a year from a string

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

Answer
/(^|\s)(\d{4})(\s|$)/gm

Matches

Acquired by the University in 1988
The 1945 vintage was superb
1492 columbus sailed the ocean blue

Ignores

There were nearly 10000 people there!
Member ID 45678
Phone Number 951-555-2563

See it in action at http://refiddle.com/10k

Comments