dongxiong1941 2012-03-20 09:22
浏览 35
已采纳

用数组值替换字符串中的模板

I have a string, that can has simple templates. And I have an array with values for replacemenet. Currently I am doing it with loop. But I want to change it to preg_replace. Can you help me?

Example:

$values = array(
    'id'   => 120,
    'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';
$output = preg_replace(...); // Hello Jim. Your ID is 120

Also preg_replace should work not only with id and name, but with any other keys. Thanks.

  • 写回答

1条回答 默认 最新

  • dqc42632 2012-03-20 09:30
    关注

    Something like the following?

    <?php
    $values = array(
        'id'   => 120,
        'name' => 'Jim'
    );
    $string = 'Hello <!name!>. Your ID is <!id!>';
    
    function foo($val) {
            return '/<!' . $val . '!>/';
    }
    
    echo preg_replace(array_map('foo', array_keys($values)), array_values($values), $string);
    

    If the whole thing is in a class:

    class Template {
            static function bar($val) {
                    return '/<!' . $val . '!>/';
            }
    
            function render($values, $string) {
                    echo preg_replace(array_map(array('Template', 'bar'), array_keys($values)), array_values($values), $string);
            }
    }
    
    $values = array(
        'id'   => 120,
        'name' => 'Jim'
    );
    $string = 'Hello <!name!>. Your ID is <!id!>';
    $T = new Template();
    $T->render($values, $string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失