【问题标题】:Replace placeholder in template with php function用php函数替换模板中的占位符
【发布时间】:2015-09-21 12:41:57
【问题描述】:

简洁明了。我不擅长正则表达式,因为我从来不理解它。但是当你看到这个简单的模板时,你会说可以用 php 括号替换 %% + 它的内容 + 像这样添加函数括号:

模板:

<html>
<head>
    <title>%getTitle%</title>
</head>
<body>
    <div class='mainStream'>
        %getLatestPostsByDate%
    </div>
</body>
</html>

它应该替换成这个:

<html>
<head>
    <title><?php getTitle();?></title>
</head>
<body>
    <div class='mainStream'>
        <?php getLatestPostsByDate();?>
    </div>
</body>
</html>

这可能吗?如果是,如何?如果有人得到一个很好的正则表达式教程,即使不是那么聪明的人也能解释它,我将非常感激。

提前致谢。

【问题讨论】:

  • 你可以使用str_replace
  • I'm not good at regex because I never understood it.我不喜欢这句话......也许你的意思是because I am lazy to learn it.?
  • 感谢您的链接 :) 我一定会学习它,因为如果您正在编码,您每天都需要它。无论我在不知道如何正则表达式的情况下这样做了多久。这太重要了。非常感谢大家! :)

标签: php regex replace


【解决方案1】:

这可能是一个好的开始。获取所有自定义标签(%%),并将其替换为 php 代码。

https://regex101.com/r/aC2hJ3/1

正则表达式:/%(\w*?)%/g。检查右侧(顶部)正则表达式的解释,并生成代码......它应该会有所帮助。

$template=file_get_contents('template.php');

    $re = "/%(\\w*?)%/"; 

    $subst = "<?php $1(); ?>"; 

    $result = preg_replace($re, $subst, $template);

file_put_contents('template.php',$result);

【讨论】:

  • 老兄,我爱你 :> 这对我来说似乎是最好的解决方案,不像其他答案不好,它们也很好,但你的对我来说是最好的解释。非常感谢。只是为了更动态的部分,而不是 file_put_contents 我使用了一个不操纵模板的技巧 -> eval('?>' . $result . '
  • Np,很高兴为您提供帮助。 :) regex101 可能是学习和练习 regex 的最佳在线资源之一,有时甚至是解决问题的现成解决方案的来源。 :)
【解决方案2】:

试试这个

$html = str_replace ('%getLatestPostsByDate%', '<?php getLatestPostsByDate();?>', $html);

如果您正在寻找通用解决方案,那么您必须使用 regex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2013-01-24
    • 2018-11-10
    • 2013-04-08
    相关资源
    最近更新 更多