doz97171 2015-07-21 11:06
浏览 25
已采纳

模板的正则表达式日期格式无效

I'm trying to replace variables like {{{month}}} in a template to the current month and {{{month+1}}} to current month + 1. That's not the hardest part of my code, except that the regex I wrote doesn't yield expected results.

$string = '{{{year}}}{{{month+1}}}';
preg_match_all('/{{{(?:([yY])ear|([mM])onth|([dD])ay)(?:(?<operation>[-|+])(?<amount>[1-9]+))?}}}/m', $string, $matches);
var_dump($matches);

Why do I have so much empty array entries? I was expecting

[0] => array('{{{year}}}', '{{{month+1}}}')
[1] => array('y', 'm')
[2] => array('', '+')
[3] => array('', '1')

What am I doing wrong?

The respond of the above code is:

array(8) {
  [0]=>
  array(2) {
    [0]=>
    string(10) "{{{year}}}"
    [1]=>
    string(13) "{{{month+1}}}"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "y"
    [1]=>
    string(0) ""
  }
  [2]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(1) "m"
  }
  [3]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
  }
  ["operation"]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(1) "+"
  }
  [4]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(1) "+"
  }
  ["amount"]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(1) "1"
  }
  [5]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(1) "1"
  }
}
  • 写回答

1条回答 默认 最新

  • douliangpo0128 2015-07-21 14:50
    关注

    You may use a "generic" character class to match the first letters of month, year and day, and then use an alternation with positive look-behinds to make sure we match what we need.

    preg_match_all('/{{{([yYmMdD])(?:(?<=[Yy])ear|(?<=[Mm])onth|(?<=[Dd])ay)(?:([-‌​+])([1-9]+))?}}}/m', $string, $matches);
    

    See IDEONE demo

    And this is the print_r view:

    Array
    (
        [0] => Array
            (
                [0] => {{{year}}}
                [1] => {{{month+1}}}
            )
    
        [1] => Array
            (
                [0] => y
                [1] => m
            )
    
        [2] => Array
            (
                [0] => 
                [1] => +
            )
    
        [3] => Array
            (
                [0] => 
                [1] => 1
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度