使用 php 将自定义 html 标签替换为超链接
我的应用程序中有一个自定义 html 标签,如下所示:
<wiki href="articletitle">Text</wiki>`
并希望将其替换为:
<a href="http://myapps/page/articletitle">Text</a>
如何在 PHP 中做到这一点?
I have a custom html tag in my apps that looks like this:
<wiki href="articletitle">Text</wiki>`
and want to replace it with this:
<a href="http://myapps/page/articletitle">Text</a>
How I can do that in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我尝试做一些非常类似的事情。我建议像躲避瘟疫一样避免使用正则表达式。这从来都不像看起来那么容易,那些极端情况会引起噩梦。
现在我倾向于 自定义标签 库本文中提到。最好的功能之一是支持隐藏或嵌套标签,如下面的代码块:
我强烈建议下载 zip 文件并查看其中包含的示例。
I'm trying to do something very similar. I recommend avoiding regEx like the plague. It's never as easy as it seems and those corner cases will cause nightmares.
Right now I'm leaning towards the Custom Tags library mentioned in this post. One of the best features is support for buried or nested tags like the code block below:
I highly recommend downloading the zip file and looking through the examples it contains.
Ruel 是对的,DOM 解析是处理它的正确方法。然而,作为正则表达式的练习,类似这样的事情应该有效:
Ruel is right, DOM parsing is the correct way to approach it. As an exercise in regex, however, something like this should work:
当合法的解析器可以更可靠地完成工作时,不要使用正则表达式。
由于您的文档包含无效标记,因此您需要在加载 html 之前平息解析器的不满。
我更喜欢使用 DOMDocument 及其声明性/不言自明的方法。
代码:(演示)
输出:
Do not use regex when a legitimate parser can do the job more reliably.
Since your document contains invalid markup, you will need to silence the parser's discontent before the html is loaded.
I prefer to use DOMDocument and its declarative/self-explanatory methods.
Code: (Demo)
Output: