【问题标题】:Execute code for each occurance of a word in a string为字符串中每个单词的出现执行代码
【发布时间】:2012-10-08 11:02:57
【问题描述】:

我有以下字符串...

HEADER*RECIPIENT MAIN *FOOTER 

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

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

我需要它按照找到它们的顺序。我的方法只适用于一页。

我怎样才能做到这一点?

【问题讨论】:

  • 您可以发布您尝试过的代码吗?这就是 StackOverflow 上的工作方式。
  • 你要执行什么代码?你想让它做什么?它会修改字符串吗?您要搜索的文本是否始终相同?
  • 作为第一个提示:查看 preg_replace_callback() 函数。如果您不想真正替换内容而只想执行其他代码,则可以使用虚拟函数。
  • $headers = explode("HEADER*", $theheaders); foreach ($headers as $header) { theheader($form); } $recipients = explode("RECIPIENT", $therecipients); foreach ($recipients as $recipient) { 收件人($form, $custtitle, $custfname, $custsname, $address1, $address2, $address3, $address4, $postcode, $custno); } $mains = explode("MAIN", $themains); foreach ($mains as $main) { main($form, $custtitle, $custsname, $accidentdate, $username); } $footers = explode("*FOOTER", $thefooters); foreach ($footers as $footer) { thefooter($form, $custno); }
  • 对不起,乱七八糟!这里不知道如何正确回复

标签: php string function foreach explode


【解决方案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.');
      }
    }
    ?>

【讨论】:

  • 对不起,我尝试使用正则表达式 /(\bHEADER\b)/ 使其正常工作,但出现以下错误... PHP 警告:function_exists() 需要参数 1是字符串,数组给定 PHP 致命错误:未捕获的异常“异常”,消息“找不到令牌处理程序”。 n堆栈跟踪:\n#0 [内部函数]:template_callback(Array)\n#1 preg_replace_callback('/(\\bHEADER\\b)/', 'template_callba...', 'HEADERRECIPIEN.. .')\n#2 templateParser('HEADERRECIPIEN...')\n#3 {main}\n 不知道为什么我会收到错误,我也不确定正则表达式
  • 一旦我摆脱了第一个 if 条件,template_callback 函数就可以完美运行,因为我的函数被称为标题而不是标题,但这是我需要的,所以谢谢@brazorf :)
猜你喜欢
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 2022-07-05
  • 2019-02-21
  • 2022-01-25
  • 1970-01-01
  • 2010-12-28
相关资源
最近更新 更多