使用 Markdown 进行链接转换 pregmatch
function makeLinks($text) {
$text = preg_replace('%(?<!href=")(((f|ht){1}(tp://|tps://))[-a-zA-^Z0-9@:\%_\+.~#?&//=]+)%i',
'<a href="\\1">\\1</a>', $text);
$text = preg_replace('%([:space:]()[{}])(www.[-a-zA-Z0-9@:\%_\+.~#?&//=]+)%i',
'\\1<a href="http://\\2">\\2</a>', $text);
return $text;
}
如果我在行的开头有这样的内容,它就会丢失: - www.website.org
(一个连字符,然后一个空格)。如果我有 - www.website.org - www.website.org 它会捕获第二个。
难道不应该被第二个 preg_replace
中的空间覆盖吗?
我还尝试了 %(\s\n\r(){})
我正在通过 markdown 运行它,但直到 (markdown(makeLinks($foo))
之后)所以我认为这不应该干扰,但是当我取消降价并且所有内容都在一行中回显时,它确实会从它们中建立链接。如果我输入 makeLinks(markdown($foo)) ,它的行为与最初相同......不会从列表项开头以 www 开头的链接中创建链接。
function makeLinks($text) {
$text = preg_replace('%(?<!href=")(((f|ht){1}(tp://|tps://))[-a-zA-^Z0-9@:\%_\+.~#?&//=]+)%i',
'<a href="\\1">\\1</a>', $text);
$text = preg_replace('%([:space:]()[{}])(www.[-a-zA-Z0-9@:\%_\+.~#?&//=]+)%i',
'\\1<a href="http://\\2">\\2</a>', $text);
return $text;
}
It misses if I have something like this: - www.website.org
(a hyphen then a space) at the beginning of a line. If I have - www.website.org - www.website.org it catches the second one.
Shouldn't that be covered by the space in the second preg_replace
?
I also tried %(\s\n\r(){})
I am running it through markdown, but not till after (markdown(makeLinks($foo))
) so I thought that shouldn't interfere, but when I take the markdown off and everything just echos out in one line, it does make links out of them. If i put makeLinks(markdown($foo))
it behaves the same as initially.. not making links out of the ones that begin with www at the beginning of list items.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是一些相当狡猾的正则表达式工作。这是我推荐用于 URL 检测的正则表达式:
应该比您现在拥有的两个更可靠。
Thats some pretty dodgy regex work there. Here is a regex I would recommend instead for URL dectection:
Should be a lot more reliable than the two you have now.