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条)

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法