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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来