Replace templates in strings by array values

后端 未结 1 459
迷失自我
迷失自我 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?

    <?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);
    
    0 讨论(0)
提交回复
热议问题