【问题标题】:Find text wrapped by specific characters and use that text as a parameter for a function查找由特定字符包裹的文本并将该文本用作函数的参数
【发布时间】:2011-08-04 22:00:59
【问题描述】:

我正在将一些 HTML 从数据库输出到页面,其中包含如下结构:

<p>Department: *|accounting|*</p>

我想查找并替换所有用 包裹的文本|和 | 并使用中间的词作为我的翻译函数的变量。

我找到了partial answer。你们能帮我解决剩下的吗?谢谢。

这有点像我正在寻找的......

$html_from_database = "<p>Department: *|accounting|*</p>";

$updated_html = preg_replace("*|(.*?)|*", translate('accounting'),$html_from_database);

这样的事情可能吗?正则表达式呢?是不是太耗费资源或太贪婪?请注意 | 之间的唯一字符和 | 将是 a-z A-Z -_ 0-9。

提前致谢。

【问题讨论】:

    标签: php regex function replace find


    【解决方案1】:

    我会分两步完成,找到匹配项,然后在每个匹配项上调用 translate 函数并构建结果字符串。类似这样的伪代码:

    matches = preg_find(".*(\|([a-zA-Z0-9\-_]*)\|).*", sourceHtml)
    foreach match in matches
        outputHtml += sourceHtml(section between previous match and this one)
        outputHtml += translate(inner group from match)
        record end position of match
    outputHtml += end of sourceHtml
    

    【讨论】:

      【解决方案2】:

      试试这个,我刚刚测试过,它可以工作:

      preg_match_all('/\|(.*?)\|/', $source, $matches);
      foreach($matches[1] as $match) {
          $source = str_replace($match,translate($match),$source);
      }
      

      $source 是您的源文本。

      【讨论】:

      • 谢谢,它工作得很好,翻译得很好。唯一的问题是 $source 仍然包裹在 | 中。和 |。我们如何调整它? [编辑:星号显然不显示在 cmets...]
      • 请改用foreach($matches[1] as $mid =&gt; $match) $source = str_replace($matches[0][$mid],translate($match),$source);
      • 谢谢,伙计!这行得通。我只是稍微更新了正则表达式,因为您的版本没有考虑星号(由于某些原因我不能放入 cmets...)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2015-08-18
      相关资源
      最近更新 更多