dongleiqiao4906 2012-10-19 11:44
浏览 50
已采纳

带有占位符的php str_replace模板

I have one array for data

    $data = array(title=>'some title', date=>1350498600, story=>'Some story');

I have a template

    $template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#"; 

All i want is to fit data into template and i know that can be done by str_replace but my problem is the date format. date format is coming from the template not from the data, in data date is stored as php date. yesterday i tried to ask the same question but i think my question wasn't clear. Anybody please help me.

  • 写回答

3条回答 默认 最新

  • douju3911 2012-10-19 11:54
    关注

    i think it won't work with str_replace easily so i'm going to use preg_replace

    $data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
    $template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#"; 
    $result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', function ($match) use($data) {
        $value = isset($data[$match[1]]) ? $data[$match[1]] : null;
    
        if (!$value) {
            // undefined variable in template throw exception or something ...
        }
    
        if (! empty($match[2]) && $match[1] == "date") {
            $value = date($match[2], $value);
        }
    
        return $value;
    }, $template);
    

    Instead of using date(m) or date(Y) you could also do things like date(d-m-Y) using this snippet

    This has the disadvantage that you can format only the date variable using this mechanism. But with a few tweaks you can extend this functionality.


    Note: If you use a PHP version below 5.3 you can't use closures but you can do the following:

    function replace_callback_variables($match) {
        global $data; // this is ugly
    
        // same code as above:
    
        $value = isset($data[$match[1]]) ? $data[$match[1]] : null;
    
        if (!$value) {
            // undefined variable in template throw exception or something ...
        }
    
        if (! empty($match[2]) && $match[1] == "date") {
            $value = date($match[2], $value);
        }
        return $value;
    }
    
    $data = array('title'=>'some title', 'date'=>1350498600, 'story'=>'Some story');
    $template = "#title#, <br>#date(d)#<br> #date(m)#<br>#date(Y)#<br> #story#";
    // pass the function name as string to preg_replace_callback
    $result = preg_replace_callback('/#(\w+)(?:\\((.*?)\\))?#/', 'replace_callback_variables', $template);
    

    You can find more information about callbacks in PHP here

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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用