dtm41506 2013-05-25 21:02
浏览 27
已采纳

模板引擎与正则表达式[关闭]

i want to wrote a simple template engine

i have a html template file :

<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
    <loop "loop_name">
        content
        <loop "loop_name2">
            content2
        </loop "loop_name2">
    </loop "loop_name">
</body>
</html>

i need to find all loops and subloops with regular expression and replace them with my predefined php variables

i wrote this but i know this is wrong way

preg_match_all("/\<loop \"(.*)\"\>(.*)\<\/loop \"(.*)\"\>/", $template_file_text, $matches);
print_r($matches);

any answers will be appreciated

  • 写回答

2条回答 默认 最新

  • dqh1984 2013-05-25 21:09
    关注

    REGEX is not capable of finding opening and matching ending tags in a way that you proably need it. Sidefact: This is something you might get ask if one wants to test your knowledge.

    You could use a XML parser. See: http://php.net/manual/de/book.xml.php

    If you want to implement this on your own than you could use a stack based algorithm that puts any opening element to a stack and pops it if you reach the matching ending tag. If you want to parse many html pages you better take the XML parser way that is built in in PHP since you will proably have to handle many situations where the page is not proverly written and error handling will become quite frustrating.

    To improve performance you could cache the output file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)