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
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题