查找由特定字符包裹的文本并将该文本用作函数的参数
我正在将一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个,我刚刚测试了它并且它有效:
$source
是您的源文本。Try this, I just tested it and it works:
$source
is your source text.我会分两步完成,找到匹配项,然后对每个匹配项调用翻译函数并构建结果字符串。像这样的伪代码:
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: