一、简单替换:

  1. javascript:
    a. 代码:
    var data = {
        'name':'lee',
        'place':'wuhan'
    }
    var str = "Hello {{name}}, Welcome to {{place}}!";
    var res = str.replace(
            /{{([\s\S]+?)}}/g,
            function(param1,param2){
                var index = param2
                return data[index]
            }
        );
    console.log(res)

    b. 输出:

    Hello lee, Welcome to wuhan!
  2. php:
    a. 代码:
    'lee',
        'place'=>'wuhan'
    );
    $str = "Hello {{name}}, Welcome to {{place}}!";
    $res = preg_replace_callback(
            "/{{([\s\S]+?)}}/",
            function($param) use($data){
                $index = $param[1];
                return $data[$index];
            },
            $str
        );
    echo $res;

    b. 输出:

    Hello lee, Welcome to wuhan!

    二、复杂替换:

  3. javascript:
    a. 代码:
    var data = {
    'name':'lee',
    'place':'wuhan'
    }
    var str = "Hello {{data.name}}, Welcome to {{data.place}}!";
    var res = str.replace(
        /{{([\s\S]+?)}}/g,
        function(param1,param2){
            var ret = eval(param2)
            return ret
        }
    );
    console.log(res)

    b. 输出:

    Hello lee, Welcome to wuhan!
  4. php:
    a. 代码:
    'lee',
        'place'=>'wuhan'
    );
    $str = "Hello {{data.name}}, Welcome to {{data.place}}!";
    $res = preg_replace_callback(
            "/{{([\s\S]+?)}}/",
            function($param) use($data){
                $raw = $param[1];
                $arr = explode('.',$raw);
                $command = 'return '.'$'.$arr[0].'[\''.$arr[1].'\'];';
                $ret = eval($command);
                return $ret;
            },
            $str
        );
    echo $res;

    b. 输出:

    Hello lee, Welcome to wuhan!