Search code examples
phpregexsubstringtext-extraction

Extract 4-digit year value 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 regex? I tried \d and that didn't work, it just came up with an error.

I'm using preg_match in LAMP 5.2


Solution

  • /(^|\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