当前位置: 首页 > 编程文章 >

PHP MVC模板引擎开发:基于正则表达式的标签解析实现

PHP MVC模板引擎开发:基于正则表达式的标签解析实现

作者:许景时间:2026-02-02 13:40:16浏览:904

模板引擎在MVC架构中负责将数据逻辑与界面展示分离,通过自定义标签解析技术降低开发维护成本。本文分享一种基于正则表达式处理多层嵌套标签的PHP模板引擎设计方案,涵盖模板加载、变量注册、缓存机制及data/list核心标签的数据提取与渲染逻辑,旨在帮助开发者理解底层实现原理。

本文目录展开

PHP MVC模板引擎开发:基于正则表达式的标签解析实现

Web系统的开发与维护工作日益繁重,采用高效的技术方案能有效节省人力物力资源,因此受到越来越多企业的青睐。


在MVC模式的构建过程中,模板引擎扮演着关键角色。它允许开发者定义具有特定语义的标签,利用技术手段将业务逻辑从视图模板中剥离。通过解析这些标签的含义,系统将控制权移交至相应的业务处理程序以获取数据,最终以模板形式呈现,使设计人员能专注于页面表现层的设计。以下是关于模板引擎的设计理念与具体实现方法的分享。


通俗来说,模板引擎的核心任务就是解读模板数据。基于对网站展现形式的分析,内容通常归纳为单条数据和列表数据两种形态。为此,可以设定如data和list等对应标签来处理这两种情况。实现的关键在于解决不同层级标签之间的相互嵌套问题,该方案基本能够覆盖80%的界面展示需求。


模板数据的解读方法多样,常见的有字符串处理和正则表达式两种方式。鉴于字符串处理在处理复杂嵌套时较为繁琐,本文选用正则表达式作为主要解析手段。下文提供具体的处理思路及参考代码,请注意这些代码可能无法直接投入生产环境使用。


模板文件解析类:


<?php
/*
* class: 模板解析类
* author: 51JS.COM-ZMM
* date: 2011.3.1
* email: 304924248@qq.com
* blog: http://www.cnblogs.com/cnzmm/
*/
class Template {
    public $html, $vars, $bTag, $eTag;
    public $bFlag='{', $eFlag='}', $pfix='zmm:';
    private $folder, $file;
    function __construct($vars=array()) {
        !empty($vars) && $this->vars = $vars;
        !empty($GLOBALS['cfg_tag_prefix']) &&
        $this->pfix = $GLOBALS['cfg_tag_prefix'].':';
        $this->bTag = $this->bFlag.$this->pfix;
        $this->eTag = $this->bFlag.'\/'.$this->pfix;
        empty(Tags::$vars) && Tags::$vars = &$this->vars;
    }
    public function LoadTpl($tpl) {
        $this->file = $this->GetTplPath($tpl);
        Tags::$file = &$this->file;
        if (is_file($this->file)) {
            if ($this->GetTplHtml()) {
                $this->SetTplTags();
            } else {
                exit('模板文件加载失败!');
            }
        } else {
            exit('模板文件['.$this->file.']不存在!');
        }
    }
    private function GetTplPath($tpl) {
        $this->folder = WEBSITE_DIRROOT.
        $GLOBALS['cfg_tpl_root'];
        return $this->folder.'/'.$tpl;
    }
    private function GetTplHtml() {
        $html = self::FmtTplHtml(file_get_contents($this->file));
        if (!empty($html)) {
            $callFunc = Tags::$prefix.'Syntax';
            $this->html = Tags::$callFunc($html, new Template());
        } else {
            exit('模板文件内容为空!');
        } return true;
    }
    static public function FmtTplHtml($html) {
        return preg_replace('/(\r)|(\n)|(\t)|(\s{2,})/is', '', $html);
    }
    public function Register($vars=array()) {
        if (is_array($vars)) {
            $this->vars = $vars;
            Tags::$vars = &$this->vars;
        }
    }
    public function Display($bool=false, $name="", $time=0) {
        if (!empty($this->html)) {
            if ($bool && !empty($name)) {
                if (!is_int($time)) $time = 600;
                $cache = new Cache($time);
                $cache->Set($name, $this->html);
            }
            echo $this->html; flush();
        } else {
            exit('模板文件内容为空!');
        }
    }
    public function SetAssign($souc, $info) {
        if (!empty($this->html)) {
            $this->html = str_ireplace($souc, self::FmtTplHtml($info), $this->html);
        } else {
            exit('模板文件内容为空!');
        }
    }
    private function SetTplTags() {
        $this->SetPanelTags(); $this->SetTrunkTags(); $this->RegHatchVars();
    }
    private function SetPanelTags() {
        $rule = $this->bTag.'([^'.$this->eFlag.']+)\/'.$this->eFlag;
        preg_match_all('/'.$rule.'/ism', $this->html, $out_matches);
        $this->TransTag($out_matches, 'panel'); unset($out_matches);
    }
    private function SetTrunkTags() {
        $rule = $this->bTag.'(\w+)\s*([^'.$this->eFlag.']*?)'.$this->eFlag.
        '((?:(?!'.$this->bTag.')[\S\s]*?|(?R))*)'.$this->eTag.'\\1\s*'.$this->eFlag;
        preg_match_all('/'.$rule.'/ism', $this->html, $out_matches);
        $this->TransTag($out_matches, 'trunk'); unset($out_matches);
    }
    private function TransTag($result, $type) {
        if (!empty($result[0])) {
            switch ($type) {
                case 'panel' : {
                    for ($i = 0; $i < count($result[0]); $i ++) {
                        $strTag = explode(' ', $result[1][$i], 2);
                        if (strpos($strTag[0], '.')) {
                            $itemArg = explode('.', $result[1][$i], 2);
                            $callFunc = Tags::$prefix.ucfirst($itemArg[0]);
                            if (method_exists('Tags', $callFunc)) {
                                $html = Tags::$callFunc(chop($itemArg[1]));
                                if ($html !== false) {
                                    $this->html = str_ireplace($result[0][$i], $html, $this->html);
                                }
                            }
                        } else {
                            $rule = '^([^\s]+)\s*([\S\s]+)$';
                            preg_match_all('/'.$rule.'/is', trim($result[1][$i]), $tmp_matches);
                            $callFunc = Tags::$prefix.ucfirst($tmp_matches[1][0]);
                            if (method_exists('Tags', $callFunc)) {
                                $html = Tags::$callFunc($tmp_matches[2][0]);
                                if ($html !== false) {
                                    $this->html = str_ireplace($result[0][$i], $html, $this->html);
                                }
                            } unset($tmp_matches);
                        }
                    } break;
                }
                case 'trunk' : {
                    for ($i = 0; $i < count($result[0]); $i ++) {
                        $callFunc = Tags::$prefix.ucfirst($result[1][$i]);
                        if (method_exists('Tags', $callFunc)) {
                            $html = Tags::$callFunc($result[2][$i], $result[3][$i]);
                            $this->html = str_ireplace($result[0][$i], $html, $this->html);
                        }
                    } break;
                }
                default: break;
            }
        } else {
            return false;
        }
    }
    private function RegHatchVars() {
        $this->SetPanelTags();
    }
    function __destruct() {}
}
?>

标签解析类:(目前暂时提供data、list两种标签的解析,说明思路)


<?php
/*
* class: 标签解析类
* author: 51JS.COM-ZMM
* date: 2011.3.2
* email: 304924248@qq.com
* blog: http://www.cnblogs.com/cnzmm/
*/
class Tags {
    static private $attrs=null;
    static public $file, $vars, $rule, $prefix='TAG_';
    static public function TAG_Syntax($html, $that) {
        $rule = $that->bTag.'if\s+([^'.$that->eFlag.']+)\s*'.$that->eFlag;
        $html = preg_replace('/'.$rule.'/ism', '
        <?php if (\\1) { ?>

', $html);


$rule = $that->bTag.'elseif\s+([^'.$that->eFlag.']+)\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php } elseif (\\1) { ?>

', $html);


$rule = $that->bTag.'else\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php } else { ?>

', $html);


$rule = $that->bTag.'loop\s+(\S+)\s+(\S+)\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php foreach (\\1 as \\2) { ?>

', $html);


$rule = $that->bTag.'loop\s+(\S+)\s+(\S+)\s+(\S+)\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php foreach (\\1 as \\2 =>\\3) { ?>
', $html);

$rule = $that->eTag.'(if|loop)\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php } ?>

', $html);


$rule = $that->bTag.'php\s*'.$that->eFlag.'((?:(?!'.


$that->bTag.')[\S\s]*?|(?R))*)'.$that->eTag.'php\s*'.$that->eFlag;


$html = preg_replace('/'.$rule.'/ism', '

<?php \\1 ?>

', $html);


return self::TAG_Execute($html);


}

static public function TAG_List($attr, $html) {


if (!empty($html)) {


if (self::TAG_HaveTag($html)) {


return self::TAG_DealTag($attr, $html, true);


} else {


return self::TAG_GetData($attr, $html, true);


}

} else {


exit('标签{list}的内容为空!');


}
}

static public function TAG_Data($attr, $html) {


if (!empty($html)) {


if (self::TAG_HaveTag($html)) {


return self::TAG_DealTag($attr, $html, false);


} else {


return self::TAG_GetData($attr, $html, false);


}

} else {


exit('标签{data}的内容为空!');


}
}

static public function TAG_Execute($html) {


ob_clean(); ob_start();


if (!empty(self::$vars)) {


is_array(self::$vars) &&


extract(self::$vars, EXTR_OVERWRITE);


}

$file_inc = WEBSITE_DIRINC.'/buffer/'.


md5(uniqid(rand(), true)).'.php';


if ($fp = fopen($file_inc, 'xb')) {


fwrite($fp, $html);


if (fclose($fp)) {


include($file_inc);


$html = ob_get_contents();


} unset($fp);


} else {


exit('模板解析文件生成失败!');


} ob_end_clean(); @unlink($file_inc);


return $html;


}

static private function TAG_HaveTag($html) {


$bool_has = false;


$tpl_ins = new Template();


self::$rule = $tpl_ins->bTag.'([^'.$tpl_ins->eFlag.']+)\/'.$tpl_ins->eFlag;


$bool_has = $bool_has || preg_match('/'.self::$rule.'/ism', $html);


self::$rule = $tpl_ins->bTag.'(\w+)\s*([^'.$tpl_ins->eFlag.']*?)'.$tpl_ins->eFlag.


'((?:(?!'.$tpl_ins->bTag.')[\S\s]*?|(?R))*)'.$tpl_ins->eTag.'\\1\s*'.$tpl_ins->eFlag;


$bool_has = $bool_has || preg_match('/'.self::$rule.'/ism', $html);


unset($tpl_ins);


return $bool_has;


}

static private function TAG_DealTag($attr, $html, $list) {


preg_match_all('/'.self::$rule.'/ism', $html, $out_matches);


if (!empty($out_matches[0])) {


$child_node = array();


for ($i = 0; $i < count($out_matches[0]); $i ++) {


$child_node[] = $out_matches[3][$i];


$html = str_ireplace($out_matches[3][$i], '{-->>child_node_'.$i.'<<--}', $html);


}

$html = self::TAG_GetData($attr, $html, $list);


for ($i = 0; $i < count($out_matches[0]); $i ++) {


$html = str_ireplace('{-->>child_node_'.$i.'<<--}', $child_node[$i], $html);


}

preg_match_all('/'.self::$rule.'/ism', $html, $tmp_matches);


if (!empty($tmp_matches[0])) {


for ($i = 0; $i < count($tmp_matches[0]); $i ++) {


$callFunc = self::$prefix.ucfirst($tmp_matches[1][$i]);


if (method_exists('Tags', $callFunc)) {


$temp = self::$callFunc($tmp_matches[2][$i], $tmp_matches[3][$i]);


$html = str_ireplace($tmp_matches[0][$i], $temp, $html);


}
}
}

unset($tmp_matches);


}

unset($out_matches); return $html;


}

static private function TAG_GetData($attr, $html, $list=false) {


if (!empty($attr)) {


$attr_ins = new Attbt($attr);


$attr_arr = $attr_ins->attrs;


if (is_array($attr_arr)) {


extract($attr_arr, EXTR_OVERWRITE);


$source = table_name($source, $column);


$rule = '\[field:\s*(\w+)\s*([^\]]*?)\s*\/?]';


preg_match_all('/'.$rule.'/is', $html, $out_matches);


$data_str = '';


$data_ins = new DataSql();


$attr_where = $attr_order = '';


if (!empty($where)) {


$where = str_replace(',', ' and ', $where);


$attr_where = ' where '. $where;


}

if (!empty($order)) {


$attr_order = ' order by '.$order;


} else {


$fed_name = '';


$fed_ins = $data_ins->GetFedNeedle($source);


$fed_cnt = $data_ins->GetFedCount($fed_ins);


for ($i = 0; $i < $fed_cnt; $i ++) {


$fed_flag = $data_ins->GetFedFlag($fed_ins, $i);


if (preg_match('/auto_increment/ism', $fed_flag)) {


$fed_name = $data_ins->GetFedName($fed_ins, $i);


break;


}
}

if (!empty($fed_name))


$attr_order = ' order by '.$fed_name.' desc';


}

if ($list == true) {


if (empty($source) && empty($sql)) {


exit('标签{list}必须指定source属性!');


}

$attr_rows = $attr_page = '';


if ($rows > 0) {


$attr_rows = ' limit 0,'.$rows;


}

if (!empty($sql)) {


$data_sql = $sql;


} else {


$data_sql = 'select * from `'.$source.'`'.


$attr_where.$attr_order.$attr_rows;


}

if ($pages=='true' && !empty($size)) {


$data_num = $data_ins->GetRecNum($data_sql);


$page_cnt = ceil($data_num / $size);


global $page;


if (!isset($page) || $page < 1) $page = 1;


if ($page > $page_cnt) $page = $page_cnt;


$data_sql = 'select * from `'.$source.'`'.$attr_where.


$attr_order.' limit '.($page-1) * $size.','.$size;


$GLOBALS['cfg_page_curr'] = $page;


$GLOBALS['cfg_page_prev'] = $page - 1;


$GLOBALS['cfg_page_next'] = $page + 1;


$GLOBALS['cfg_page_nums'] = $page_cnt;


if (function_exists('list_pagelink')) {


$GLOBALS['cfg_page_list'] = list_pagelink($page, $page_cnt, 2);


}
}

$data_idx = 0;


$data_ret = $data_ins->SqlCmdExec($data_sql);


while ($row = $data_ins->GetRecArr($data_ret)) {


if ($skip > 0 && !empty($flag)) {


$data_idx != 0 &&


$data_idx % $skip == 0 &&


$data_str .= $flag;


}

$data_tmp = $html;


$data_tmp = str_ireplace('@idx', $data_idx, $data_tmp);


for ($i = 0; $i < count($out_matches[0]); $i ++) {


$data_tmp = str_ireplace($out_matches[0][$i],


$row[$out_matches[1][$i]], $data_tmp);


}

$data_str .= $data_tmp; $data_idx ++;


}

} else {


if (empty($source)) {


exit('标签{data}必须指定source属性!');


}

$data_sql = 'select * from `'.$source.


'`'.$attr_where.$attr_order;


$row = $data_ins->GetOneRec($data_sql);


if (is_array($row)) {


$data_tmp = $html;


for ($i = 0; $i < count($out_matches[0]); $i ++) {


$data_val = $row[$out_matches[1][$i]];


if (empty($out_matches[2][$i])) {


$data_tmp = str_ireplace($out_matches[0][$i], $data_val, $data_tmp);


} else {


$attr_str = $out_matches[2][$i];


$attr_ins = new Attbt($attr_str);


$func_txt = $attr_ins->attrs['function'];


if (!empty($func_txt)) {


$func_tmp = explode('(', $func_txt);


if (function_exists($func_tmp[0])) {


eval('$func_ret ='.str_ireplace('@me',


'\''.$data_val.'\'', $func_txt));


$data_tmp = str_ireplace($out_matches[0][$i], $func_ret, $data_tmp);


} else {


exit('调用了不存在的函数!');


}

} else {


exit('标签设置属性无效!');


}
}
}

$data_str .= $data_tmp;


}
}

unset($data_ins);


return $data_str;


} else {


exit('标签设置属性无效!');


}

} else {


exit('没有设置标签属性!');


}
}

static public function __callStatic($name, $args) {


exit('标签{'.$name.'}不存在!');


}
}
?>
上一篇
PHP对象串行化与魔术方法详解

对象串行化是将对象转化为二进制串以便在网络传输或存储到文件、数据库中,到达另一端后再还原为原对象的过程。PHP通过serialize()进行串行化,返回字符串;使用unserialize()进行反串行化,恢复对象。在PHP5中,可通过定义__sleep()和__wakeup()魔术方法来控制串行化时的属性筛选及反串行化后的初始化动作。

下一篇
PHP非递归遍历目录下所有文件的实现

在PHP中遍历包含子目录的文件时,通常使用递归方法。本文介绍利用栈结构实现的非递归方案,通过循环处理数组元素来替代函数自调用。相比递归,该方法避免了深层嵌套带来的性能影响,但需注意文件打印顺序可能与系统扫描结果相反,可通过反转数组顺序解决。

相关文章

更多
PHP常用表单验证正则表达式集合

本文整理了PHP中用于常见表单数据验证的正则表达式代码片段。涵盖了电子邮件、网址、QQ号、邮编、身份证号、中英文字符、手机号及固定电话的格式校验逻辑,并包含一个用于检测不安全字符的安全过滤函数,帮助开发者快速实现前端输入后的后端基础合法性检查。

2025.10.20 990
PHP使用正则表达式提取手机号及识别运营商

本文介绍利用PHP正则表达式从文本中批量提取手机号码并自动识别所属运营商的方法。通过预定义的号段规则,脚本不仅能匹配11位移动号码,还能区分中国电信、中国移动和中国联通等类型,同时支持识别固定电话及小灵通等可能存在的号码格式,实现高效便捷的字符串解析。

2025.11.29 983
PHP正则表达式过滤HTML标签属性示例

在PHP开发中,内置函数往往过于严格地清除所有HTML内容,而实际场景如数据采集时,常需保留特定属性并移除其他冗余部分。本文通过多个`preg_replace`实例,演示如何精准过滤除src外的所有img属性、保留alt和src、仅处理alt属性,以及全面清理HTML标签与特殊字符的完整方案,帮助开发者灵活控制输出内容的结构。

2025.07.17 983
PHP过滤危险HTML代码的自定义函数实现

本文介绍了一个名为uhtml的PHP自定义函数,用于清理字符串中的危险HTML代码。该函数通过正则表达式过滤多余空白、潜在的恶意布局标签以及JavaScript的on事件属性,从而提升内容安全性。

2026.06.09 945
利用PHP内置服务器调试正则匹配结果

自PHP v5.4起,PHP提供了简易的内置Web服务器,无需搭建完整环境即可运行代码。通过启动该服务并访问包含preg_match函数的脚本,开发者可以直观查看正则表达式的匹配结果及偏移量信息,从而高效进行代码调试与验证。

2025.01.11 944
PHP常用字符串处理函数与正则表达式实例解析

本文汇总了PHP中常用的字符串处理函数及其应用场景。内容涵盖基础输出控制如echo与printf,大小写转换如ucfirst与ucwords,以及空格去除的ltrim和rtrim。同时深入讲解了正则表达式的实际应用,包括使用preg_replace进行模式替换、利用preg_split分割字符串,以及通过protected_context中的代码示例展示复杂正则匹配与字符转义技巧,为开发者提供实用的代码参考。

2025.01.15 883

专题推荐

更多
PHP 模板引擎选型与页面渲染

已有项目先按实际引擎找入门例子,核对变量如何传进模板。想了解引擎内部时,再看标签解析与渲染思路。

PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

在线工具箱

更多
PHP 常用函数手册速查
PHP 常用函数手册速查

按函数名或关键词查阅整理的 PHP 常用函数信息。

正则测试
正则测试

使用输入的正则表达式测试文本,观察匹配结果。

键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。