0

我有以下字符串...

HEADER*RECIPIENT MAIN *FOOTER 

我想知道如何使用 PHP 循环遍历这个字符串并在每次出现 HEADER*、*FOOTER、MAIN 和 RECIPIENT 时执行一个函数。

在爆炸字符串后,我自己尝试使用基本的 for-each 循环,但我发现它将所有元素组合在一起。

我需要它遵循它们被发现的顺序。我的方法只适用于一页。

我怎样才能做到这一点?

4

1 回答 1

1

这就是我在多年前开发的一个旧框架中使用preg_replace_callback做一个简单的模板解析器的方式。

基本上,您为您的 templateParser 提供源模板,并在回调函数中处理令牌的出现。这是一个骨架,显然您应该对其进行自定义实现,并设计您的正则表达式以匹配 HEADER*、*FOOTER 等标记。

<?php
    /**
     *  @param string $tpl
     *    The template source, as a string.
     */
    function templateParser($tpl) {
      $tokenRegex = "/your_token_regex/";
      $tpl = preg_replace_callback($tokenRegex , 'template_callback', $tpl);
      return $tpl;
    }

    function template_callback($matches) {
      $element = $matches[0];
      // Element is the matched token inside your template
      if (function_exists($element)) {
        return $element();
      } else if ($element == 'HEADER*') {
        return your_header_handler();
      } else {
        throw new Exception('Token handler not found.');
      }
    }
    ?>
于 2012-10-08T11:48:24.863 回答