默默简单的写了一个模板引擎_PHP教程
引擎文件
* 默默基于Discuz的模板引擎开发的OOP类模板引擎,可支持模板缓存并生成hash的md5值。由hash值来判断模板是否被修改,假如被修改则重新生成缓存文件,假如没有被修改,则直接调用缓存文件.
* 版本:1.0.0.1 beta 测试版
*/
class mmtp{
var $left_tags="{";
var $right_tags="}";
var $tp_suffix=".html";
var $cache_suffix=".tpl";
var $tp_dir="./";
var $cache_dir="./";
/**
* 允许循环嵌套的次数,默认为5
*
* @var unknown_type
*/
var $nest = 5;
/**
* 模板路径
*
* @param unknown_type $tp_dir
* @return mmtp
*/
function __setdir($tp_dir){
if(file_exists($tp_dir)){
$this->tp_dir=$tp_dir;
}else{
$this->error("模板路径不存在");
}
}
/**
* 设置缓存目录
*
* @param unknown_type $cache_dir
*/
function __setcdir($cache_dir){
if(file_exists($cache_dir)){
$this->cache_dir=$cache_dir;
}else{
$this->error("缓存路径不存在");
}
}
/**
* 输出错误信息
*
* @param unknown_type $msg
*/
function error($msg){
print "
}
/**
* 解析模板
*
* @param unknown_type $file
*/
function tp($file){
$tp_path=$this->tp_dir.$file.$this->tp_suffix;
$fp=fopen($tp_path,"rb");
if(!$this->file_test($tp_path,"r") && !$this->match_hash($file)){
$template=$this->file_read($tp_path);
$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
$template = preg_replace("/\/s", "{\\1}", $template);
$template = preg_replace("/\{lang\s+(.+?)\}/ies", "languagevar('\\1')", $template);
$template = str_replace("{LF}", "=\"\\n\"?>", $template);
$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "=\\1?>", $template);
$template = preg_replace("/$var_regexp/es", "\$this->addquote('=\\1?>')", $template);
$template = preg_replace("/\\?\>/es", "\$this->addquote('=\\1?>')", $template);
$template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_]+)\}[\n\r\t]*/is", "\n include('".$this->cache_dir."\\1".$this->cache_suffix."'); ?>\n", $template);
$template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n include('".$this->cache_dir."\\1".$$this->cache_suffix."'); ?>\n", $template);
$template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n \\1 ?>\n','')", $template);
$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n echo \\1; ?>\n','')", $template);
$template = preg_replace("/[\n\r\t]*\{elseif\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n } elseif(\\1) { ?>\n','')", $template);
$template = preg_replace("/[\n\r\t]*\{else\}[\n\r\t]*/is", "\n } else { ?>\n", $template);
for($i = 0; $i nest; $i++) {
$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "\$this->stripvtags('\n if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\n\\3\n } } ?>\n')", $template);
$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "\$this->stripvtags('\n if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\n\\4\n } } ?>\n')", $template);
$template = preg_replace("/[\n\r\t]*\{if\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{\/if\}[\n\r\t]*/ies", "\$this->stripvtags('\n if(\\1) { ?>','\n\\2\n } ?>\n')", $template);
}
$template = preg_replace("/\{$const_regexp\}/s", "=\\1?>", $template);
$template = preg_replace("/ \?\>[\n\r]*\ $hash=$this->file_hash($tp_path);
$head_hash="";
$foot_time="";
$this->file_write($this->cache_dir.$file.".tpl",$head_hash.$template.$foot_time);
}
}
/**
* 检查文件是否存在并且有读取权限
*
* @param unknown_type $path
*/
function file_test($path,$method){
if(!file_exists($path) || !fopen($path,$method)){
$this->error("模板文件不存在,或没有操作权限");
return false;
}
}
/**
* 读取文件内容
*
* @param unknown_type $path
* @return unknown
*/
function file_read($path,$length=0){
if(!$this->file_test($path,"r+")){
$fp=@fopen($path,"r+");
if($length==0){
$contents=@fread($fp,filesize($path));
}else{
$contents=@fread($fp,$length);
}
fclose($fp);
return $contents;
}
}
/**
* 写入文件内容
*
* @param unknown_type $path
* @param unknown_type $puts
*/
function file_write($path,$puts){
if(!$this->file_test($path,"w+")){
$fp=@fopen($path,"w+");
@fwrite($fp,$puts);
fclose($fp);
}
}
/**
* 计算文件的hash
*
* @param unknown_type $path
* @return unknown
*/
function file_hash($path){
return md5_file($path);
}
/**
* 对比模板文件与缓存文件的hash值
*
* @param unknown_type $file
* @return unknown
*/
function match_hash($file){
$read_hash=$this->file_read($this->cache_dir.$file.$this->cache_suffix,46);
$html_hash=$this->file_hash($this->tp_dir.$file.$this->tp_suffix);
if(preg_match("/".$html_hash."/i",$read_hash)){
return true;
}
}
function addquote($var) {
return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}
function transamp($str) {
$str = str_replace('&', '&', $str);
$str = str_replace('&', '&', $str);
$str = str_replace('\"', '"', $str);
return $str;
}
function stripvtags($expr, $statement) {
$expr = str_replace("\\\"", "\"", preg_replace("/\/s", "\\1", $expr));
$statement = str_replace("\\\"", "\"", $statement);
return $expr.$statement;
}
}
$tp=new mmtp();
$tp->__setdir("./");
$tp->__setcdir("./cache/");
$tp->tp("index1");
$_GET[it]=sdhkadajksdhajdhkajsdhjkasdjkasdhasjdhkjsadhk;
$name=2;
$head="欢迎使用MoMo模板引擎";
include("./cache/index1.tpl");
?>
模板index.html
模板index1.html
{if $name==1}
你好
{else}
谢谢
{/if}
这个模板是默默今天下午写的,写的比较仓促,也许存在漏洞,这个版本只是测试版,以后我会逐渐的去完善,先发出来,当作一个前瞻.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 여러 라이브러리가 있습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다
