PHP中正则表达式回顾(4)--编写一个很是简单并且山寨的smarty模板引擎

    PHP的正则表达式今天就结束了,遥想几年前初次接触的时候,感受这玩意真心玩不转啊,而时至今日,感受这也没有什么难以理解的,确实仍是有很大进步的,尤为是对smarty模板引擎有了一个更为清晰的认识。正则表达式学到最后,老是会抛出这个编写一个山寨的smarty模板引擎的话题出来练练手,今天就在大师的指导下,编写了这么一个山寨smarty,做为此次复习正则的一个句点吧。
php

<?php 

class template{

	//存储模板引擎源文件目录
	private $templateDir;
	//编译后的文件目录
	private $compileDir;
	//边界符号	左边界
	private $leftTag="{#";
	//边界符号	右边界
	private $rightTag="#}";
	//当前正在编译的模板文件名
	private $currentTemp='';
	//当前源文件中的html代码
	private $outputHtml;
	//变量池
	private $varPool=array();

	//构造函数 传入模板文件目录  编译文件目录
	public function __construct($templateDir,$compileDir,$leftTag=null,$rightTag=null){
		$this->templateDir=$templateDir;
		$this->compileDir=$compileDir;
		if(!empty($leftTag))	$this->leftTag=$leftTag;
		if(!empty($rightTag))	$this->rightTag=$rightTag;
	}
	//往变量池中写入数据
	public function assign($tag,$var){
		$this->varPool[$tag]=$var;
	}
	//从变量池中取出数据的方法
	public function getVar($tag){
		return $this->varPool[$tag];
	}
	//得到源文件内容
	public function getSourceTemplate($templateName,$ext='.html'){
		$this->currentTemp=$templateName;
		//拿到完整路径
		$sourceFilename=$this->templateDir.$templateName.$ext;
		//得到源文件中的html代码
		$this->outputHtml=file_get_contents($sourceFilename);
	}
	//建立编译文件
	public function compileTemplate($templateName=null,$ext='.html'){
		$templateName=empty($templateName)?$this->currentTemp:$templateName;
		//开始正则匹配
		$pattern	=	'/'.preg_quote($this->leftTag);
		$pattern	.=	' *\$([a-zA-Z]\w*) *';
		$pattern	.=	preg_quote($this->rightTag).'/';

		$this->outputHtml=preg_replace($pattern, '<?php echo $this->getVar(\'$1\') ?>', $this->outputHtml);
		//编译文件完整路径
		$compileFilename=$this->compileDir.md5($templateName).$ext;
		file_put_contents($compileFilename, $this->outputHtml);	
	}
	//模板输出
	public function display($templateName=null,$ext='.html'){
		$templateName=empty($templateName)?$this->currentTemp:$templateName;
		include_once $this->compileDir.md5($templateName).$ext;
	}
}

	$baseDir=str_replace('\\', '/', dirname(__FILE__));
	$temp=new template($baseDir.'/source/',$baseDir.'/compiled/');
	$temp->assign('title','学PHP的小蚂蚁');
	$temp->assign('name','小蚂蚁');
	$temp->getSourceTemplate('index');
	$temp->compileTemplate();
	$temp->display();
 ?>

    类库很简单,主要是领悟一下模板引擎的工做思路,顺便在领悟一下OOP的编程思路。
html

    preg_match_all()不但能获取总模式,还能将子模式匹配出来。0键为总模式匹配结果。1~n为子模式。
正则表达式

    preg_replace()同理  $1 和 \\1 是同样的。
编程

<! doctype <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>{#$title#}</title>
</head>
<body>
	个人名字是:{#$name#}
</body>
</html>

    正则表达式结束。over.
函数

相关文章
相关标签/搜索