preg_replace - 仅在被空格包围时匹配
这是我现有的代码:
preg_replace("!((([a-z]{3,5}://))". "[-a-z0-9.]{2,}\.[a-z]{2,4}". "(:[0-9]+)?". "(/([^\s]*[^\s,.])?)?". "(\?([^\s]*[^\s,.])?)?)!i", "<a target=\"_blank\" href=\"\\1\">\\1</a>", $s);
它需要一个链接并将其转换为 HTML。
问题是有时我会得到一个我不想转换为 HTML 的 URL。例如:
<img src="http://www.domain.com/img.png" />
这样就会变成:
<img src="<a target="_blank" href ...
防止这种情况的最佳方法是什么?我认为仅在空间之间建立链接可能会效果很好。我将如何更改 preg_replace ?
Here's my existing code:
preg_replace("!((([a-z]{3,5}://))". "[-a-z0-9.]{2,}\.[a-z]{2,4}". "(:[0-9]+)?". "(/([^\s]*[^\s,.])?)?". "(\?([^\s]*[^\s,.])?)?)!i", "<a target=\"_blank\" href=\"\\1\">\\1</a>", $s);
It takes a link and turns it into HTML.
The problem is that sometimes I get a URL that I don't want to turn into HTML. For example:
<img src="http://www.domain.com/img.png" />
so that would turn into:
<img src="<a target="_blank" href ...
What is the best way to prevent this? I think only taking links between a space might work well. How would I alter the preg_replace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用单词边界 (
\b
)。尽管我的首选技术是仅在文本节点中搜索,这样您就不必处理序列化的 HTML。
如果您决定解析 HTML,DOMDocument 非常方便。
You could use word boundaries (
\b
).Though my preferred technique would be to search in text nodes only so you don't ever have to deal with serialised HTML.
If you decide to parse the HTML, DOMDocument is quite handy.