查找由特定字符包裹的文本并将该文本用作函数的参数

发布于 2024-11-01 06:28:26 字数 635 浏览 0 评论 0原文

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

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

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

我找到了部分答案。你们能帮我解决剩下的事情吗?谢谢。

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

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

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

这样的事情可能吗?正则表达式怎么样?是不是资源太密集或者太贪婪了?请注意 | 之间的唯一字符| 将为 az AZ -_ 0-9。

提前致谢。

I'm outputting some HTML from a database to a page, containing constructions like this:

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

I would like to find and replace all text wrapped with | and | and use the word in between as a variable for my translate function.

I've found a partial answer. Could you guys help me out with the rest? Thanks.

This is somewhat what I'm looking for...

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

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

Is something like this possible? What about the regex? Is it not too resource intensive or to greedy? Please note that the only characters between | and | will be a-z A-Z -_ 0-9.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠意 2024-11-08 06:28:27

试试这个,我刚刚测试了它并且它有效:

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

$source 是您的源文本。

Try this, I just tested it and it works:

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

$source is your source text.

岁月如刀 2024-11-08 06:28:27

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

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

I would do it in two steps, find the matches, then call the translate function on each one and build up the resulting string. Something like this pseudocode:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文