Replace templates in strings by array values

后端 未结 1 454
迷失自我
迷失自我 2021-01-26 16:47

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

1条回答
  •  隐瞒了意图╮
    2021-01-26 17:06

    Something like the following?

     120,
        'name' => 'Jim'
    );
    $string = 'Hello . Your ID is ';
    
    function foo($val) {
            return '//';
    }
    
    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 '//';
            }
    
            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 . Your ID is ';
    $T = new Template();
    $T->render($values, $string);
    

    0 讨论(0)
提交回复
热议问题