PHP 正则表达式 实现简单的模板数据渲染

方法:

<?php

function web_html1($file=null, array $vars = null){
    
    
   if(!$file){
    
    
       echo 'file:路径不能为空';
       return ;
   }
    
    $template_content =  file_get_contents($file);
    preg_match_all("/\[\{include (.*?)\}\]/",$template_content,$out);//匹配aa;
    $var=[
        'include'
    ];
    foreach ($var as $key => $value) {
    
    
        preg_match_all("/\[\{
      
      $value (.*?)\}\]/",$template_content,$out);
        // print_r($out[1]);
        foreach ($out[1] as $name => $vars) {
    
    
            if(file_exists($vars)){
    
    
                $include =  file_get_contents($vars);
            }
            $template_content = preg_replace("/\[\{
      
      $value $vars\}\]/",$include?$include:'no',$template_content);
            // echo $vars;
        }
    }
    echo $template_content;
}
function evall($code){
    
    
    return eval($code);
}

function web_html($file=null, array $vars = null){
    
    
    if(!$file){
    
    
        echo 'file:路径不能为空';
        return ;
    }
     
     $template_content =  file_get_contents($file);
     preg_match_all("/\[\((.*?)\)\]/",$template_content,$out);//匹配aa;
    $content = preg_replace('/\[\{\$([a-zA-Z_][a-zA-Z0-9_]*)\}\]/','<?php echo $tmpValue["$1"]; ?>',$template_content);
    // echo $content;
    if(!file_exists('compile')){
    
    
        mkdir('compile');
    }
    file_put_contents("compile/".md5($file).".php",$content);

    $tmpValue=$vars;
    include "compile/".md5($file).".php";
 }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>[{$title}]</title>
</head>
<body>
    
</body>
</html>

方法调用:

web_html('404.html',['title'=>'嘎嘎嘎嘎']);

能帮到你我很高兴

猜你喜欢

转载自blog.csdn.net/weixin_44296452/article/details/113351399