Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jul 2004
    Location
    Tampa
    Posts
    223
    Thanks
    23
    Thanked 0 Times in 0 Posts

    preg_match extract date from string

    I need to figure out how to extract a date out of a string. Sometimes it is at the beginning, sometimes it is in the middle with a space on each side. I have my preg_match pulling out the year, but only at the beginning of the string.

    PHP Code:
    preg_match('/^\d{4} /',$title,$matches); 
    If they put anything before the year it doesn't see the year. I can't quite figure out how to pull the year if it isn't at the beginning of the string. Any help would be great.

    Thank you.

  • #2
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,535
    Thanks
    45
    Thanked 259 Times in 256 Posts
    '/^\d{4} /' means search for 4 digits followed by a space at the beginning of the string. Drop the ^ to have it search for 4 consecutive digits followed by a space anywhere.

  • Users who have thanked Keleth for this post:

    dprichard (11-07-2010)

  • #3
    Regular Coder
    Join Date
    Jul 2004
    Location
    Tampa
    Posts
    223
    Thanks
    23
    Thanked 0 Times in 0 Posts
    Thank you that worked. What is the difference between /\d{4} / and /[0-9]{4} /

    I get the same result with both.

  • #4
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,535
    Thanks
    45
    Thanked 259 Times in 256 Posts
    There's no difference. \d means digit, and [0-9] means the digits 0 through 9, which is all of um


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •