Home > php教程 > php手册 > body text

模版小例子

WBOY
Release: 2016-06-06 20:09:14
Original
1271 people have browsed it

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': '色情场所'}
);
//"您的部落名字:天上人间,申请修改为:,失败原因: 色情场所"
Copy after login

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'=>'色情') );
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!