PHP date_parse_from_format( ) alternative in PHP 5.2

前端 未结 5 665
你的背包
你的背包 2021-01-03 01:20

Since date_parse_from_format( ) is available only in PHP 5.3, I need to write a function that mimics its behaviour in PHP 5.2.

Is it possible to write this function

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 02:04

    If you want it to be exactly like PHP 5.3 function, you're gonna need a lot of code. I'd start with something like this:

    $format = '\Y: Y-m-d';
    var_dump($format);
    
    $date = date($format);
    var_dump($date);
    
    // reverse engineer date formats
    $keys = array(
        'Y' => array('year', '\d{4}'),
        'm' => array('month', '\d{2}'),
        'd' => array('day', '\d{2}'),
        'j' => array('day', '\d{1,2}'),
        'n' => array('month', '\d{1,2}'),
        'M' => array('month', '[A-Z][a-z]{2}'),
        'F' => array('month', '[A-Z][a-z]{2,8}'),
        'D' => array('day', '[A-Z][a-z]{2}'),
        // etc etc etc
    );
    
    // convert format string to regex
    $regex = '';
    $chars = str_split($format);
    foreach ( $chars AS $n => $char ) {
        $lastChar = isset($chars[$n-1]) ? $chars[$n-1] : '';
        $skipCurrent = '\\' == $lastChar;
        if ( !$skipCurrent && isset($keys[$char]) ) {
            $regex .= '(?P<'.$keys[$char][0].'>'.$keys[$char][1].')';
        }
        else if ( '\\' == $char ) {
            $regex .= $char;
        }
        else {
            $regex .= preg_quote($char);
        }
    }
    
    var_dump($regex);
    
    // now try to match it
    if ( preg_match('#^'.$regex.'$#', $date, $matches) ) {
        foreach ( $matches AS $k => $v ) if ( is_int($k) ) unset($matches[$k]);
        print_r($matches);
    }
    else {
        echo 'invalid date "'.$date.'" for format "'.$format.'"'."\n";
    }
    

    Result:

    string(9) "\Y: Y-m-d"
    string(13) "Y: 2011-07-12"
    string(51) "\Y\: (?P\d{4})-(?P\d{2})-(?P\d{2})"
    Array
    (
        [year] => 2011
        [month] => 07
        [day] => 12
    )
    

    Incomplete and imperfect.

提交回复
热议问题