1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development PHP: extract set of numbers from a string

Discussion in 'Software' started by ajack, 22 Nov 2007.

  1. ajack

    ajack rox

    Joined:
    17 Apr 2003
    Posts:
    2,695
    Likes Received:
    2
    OK so basically I have a string which represents a date but the formatting is non-uniform (i.e. it could be '2000', '12th January 1999', '01-01-2000', etc. (The year will always be a 4 digit number though)) So I need to extract just the year from this string in PHP. Clearly a regex is needed but tbh I've only ever used them very briefly in the past so a nudge in the right direction would be appreciated :)
     
  2. mutznutz

    mutznutz Cos Ive got a beard u label me evil

    Joined:
    18 Nov 2007
    Posts:
    267
    Likes Received:
    0
    You could do this

    $test = explode("-",$string_u_want_to_get);
    $year = $test[2];
     
  3. Zut

    Zut What's a Dremel?

    Joined:
    5 Feb 2005
    Posts:
    137
    Likes Received:
    0
    Use 'strtotime' to parse the number in whatever format, to turn it into an integer timestamp. Then you can use 'date' to extract the token you need. e.g.

    PHP:
    $fuzzyDate "12th Jan 1999"
    $timestamp strtotime($fuzzyDate);

    $year date("Y"$timestamp);         // Will be "1999"
    $month date("m"$timestamp);        // ..."01"
    $dayOfWeek date("l"$timestamp);    // ..."Tuesday"
    Have fun!
     
    Last edited: 22 Nov 2007
  4. Jamie

    Jamie ex-Bit-Tech code junkie

    Joined:
    12 Mar 2001
    Posts:
    8,180
    Likes Received:
    54
    PHP:
    $str_date "12th August 2007";
    $matches = array();
    if (
    preg_match('/(\d{4})/'$str_date$matches)) {
        
    $year $matches[1];
    }
    print_r((int)$year);
     
  5. ajack

    ajack rox

    Joined:
    17 Apr 2003
    Posts:
    2,695
    Likes Received:
    2
    Wicked, last 2 work great, thanks dudes :)

    mutznuts, that would only work if the date was 'xx-xx-xxxx' which (as in my first post), that is not always going to be the case.
     
  6. mutznutz

    mutznutz Cos Ive got a beard u label me evil

    Joined:
    18 Nov 2007
    Posts:
    267
    Likes Received:
    0
    Apologies, didn't read it quite right :)
     

Share This Page