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 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动