【问题标题】:Preg_replace index in array in replacement with pattern $arr[{...}]Preg_replace 数组中的索引替换为模式 $arr[{...}]
【发布时间】:2014-11-20 10:10:02
【问题描述】:
$month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',  'August', 'September', 'October', 'November', 'December'];
$str = "The fly went away in 1990-11-20";
$pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
$replacement = array('${3}.'.'$month[\2 -1]<-- I don't know'.' ${1}');
$res = preg_replace($pattern, $replacement, $str);
echo $res;

结果应该是“The fly away in 20.November 1990”。 (我知道模式可能是 0000-00-00。但现在没关系)。这里的“$month[\2 -1]”的替代品是什么?

【问题讨论】:

    标签: php arrays replace preg-replace


    【解决方案1】:

    您不能直接使用 preg_replace。试试这个

    function doReplace($matches) {
        $month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',  'August', 'September', 'October', 'November', 'December'];
        return $matches[3] . ' ' . $month[$matches[2] - 1] . ' ' . $matches[1];
    }
    
    $str = "The fly went away in 1990-11-20";
    $pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
    $res = preg_replace_callback($pattern, 'doReplace', $str);
    echo $res;
    

    使用preg_replace_callback - 请参阅手册了解更多信息。

    【讨论】:

    • 这个答案很有用! (抱歉,目前我无法投票赞成这个答案)
    【解决方案2】:

    使用preg_replace_callback():

    $str = preg_replace_callback(
               $pattern,
               function (array $matches) use ($month) {
                  return $matches[3].'.'.$month[$matches[2]-1].' '.$matches[1];
               },
               $str
           );
    

    【讨论】:

      【解决方案3】:

      试试这个工作示例,它会给你想要的输出

          //echo date('d.F Y',strtotime('1990-11-20 00:00:00'));
          $month = array('','January','February','March', 'April', 'May', 'June', 'July',  'August', 'September', 'October', 'November', 'December');
          $str = "The fly went away in 1990-11-20";
          $pattern = array('/(\d{4})-(\d{1,2})-(\d{1,2})/');
          $replacement = array('${3}.'.$month[12-1].' ${1}');
          $res = preg_replace($pattern, $replacement, $str);
          echo $res;
      

      【讨论】:

      • 日期2014-05-15怎么样?
      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2011-03-30
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多