dongzongxun8491 2009-11-10 17:07
浏览 31
已采纳

简单的字符串转换

I have a website where I need to parse date/time strings from receipts. These can be in a variety of different formats -- for instance, one string could be '11/04/2009 12:46PM', while another could be 'Mar06'09 10:57AM'. I need to get a standard date/time string out of them to do a database insert.

I'd like to avoid writing new php code for each client to parse their string. Something I do elsewhere is store a regular expression in a database field -- that way, in order to validate data, I can just do

<?php

if ( ! preg_match($row['regex'], $variable_user_input) ) { ... }

?> 

So if I need to add a client that has a different validation criteria, I just have to write a new regex, which goes in the client database record, instead of writing, testing, and deploying new php code on the website. It's a more robust system.

Is there something like a regular expression, when I can input a string, input another transformation string, and get my date-time as output?

  • 写回答

2条回答 默认 最新

  • duanpai1920 2009-11-10 17:29
    关注

    you can use named subgroups in your regular expressions to decouple the parser from concrete formats

    function parse_date($date, $regexps) {
         foreach($regexps as $re)
            if(preg_match($re, $date, $m))
                return strtotime("{$m['year']}-{$m['month']}-{$m['day']} {$m['time']}");
    }
    
    
    $formats = array(
        "~(?P<month>[a-z]+)(?P<day>\d\d)'(?P<year>\d\d) +(?P<time>[\d:APM]+)~i",
        "~(?P<month>\d\d)/(?P<day>\d\d)/(?P<year>\d\d\d?\d?) +(?P<time>[\d:APM]+)~i"
    );
    
    
    echo date("d m Y H i", parse_date("Mar06'09 10:57AM", $formats));
    echo date("d m Y H i", parse_date('11/04/2009 12:46PM', $formats));
    

    // edit

    named patterns are quite sparsely documented, this is all i could find

    It is possible to name the subpattern with (?Ppattern) since PHP 4.3.3. Array with matches will contain the match indexed by the string alongside the match indexed by a number, then.

    http://www.php.net/manual/en/regexp.reference.subpatterns.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算