Home >php教程 >php手册 >模版小例子

模版小例子

WBOY
WBOYOriginal
2016-06-06 20:09:141339browse

javascript: function templete(str, data) { return str.replace(/({%)+([^({%)]\w*)(%})+/ig, function(all, left, key){ if(data[key]){ return data[key]; }else{ return ''; } });}templete( '您的部落名字:{%name%},申请修改为:{%oname%},失败原因:

javascript:

function templete(str, data) {
    return str.replace(/({%)+([^({%)]\w*)(%})+/ig, function(all, left, key){ 
        if(data[key]){
            return data[key];
        }else{
            return '';
        }
    });
}
templete(
    '您的部落名字:{%name%},申请修改为:{%oname%},失败原因: {%reson%}', 
    {'name' : '天上人间', 'reson': '色情场所'}
);
//"您的部落名字:天上人间,申请修改为:,失败原因: 色情场所"

php稍微麻烦一点:

<?php function template($str, $arr){
    $callback = function($matchs) use ($arr){
        return replace_callback($matchs, $arr);
    };  
    return preg_replace_callback('/({%)+([^({%)]\w*)(%})+/', $callback, $str);
}                                                                                                                                                                                                           
function replace_callback($matchs, $arr){
    if(isset($arr[$matchs[2]])) {
        var_dump($arr[$matchs[2]]);
        return $arr[$matchs[2]];
    }else{
        return ''; 
    }   
}
$res = template('您的部落名字:{%name%},申请修改为:{%oname%},失败原因: {%reson%}', array('name'=>'天上人间', 'reson'=>'色情') );
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn