PHP自动链接(如果尚未链接) [英] PHP autolink if not already linked

查看:60
本文介绍了PHP自动链接(如果尚未链接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此问题类似:

My question is similar to this question:

如何模仿StackOverflow自动链接行为

但是,此解决方案不适用于可能已经包含链接的混合内容-A标记<a href="http://stackoverflow.com">My Link</a>内已经存在的所有URL都被压缩到<a href="<a href="http://stackoverflow.com">stackoverflow.com</a>">My Link</a>

However this solution doesn't work for mixed content that may already contain links - any URLs already inside of A tags <a href="http://stackoverflow.com">My Link</a> are being mangled into <a href="<a href="http://stackoverflow.com">stackoverflow.com</a>">My Link</a>

这是所需的行为:

之前

https://stackoverflow.com/ is a wonderful URL.

<a href="https://stackoverflow.com/">Has already been linked.</a>

之后

<a href="https://stackoverflow.com/">https://stackoverflow.com/</a> is a wonderful URL.

<a href="https://stackoverflow.com/">Has already been linked.</a>

推荐答案

在ta DOM解析器中将字符串作为HTML加载,遍历文本节点并检查URL.确保文本节点的父级不是<a>标记,因此您知道要获取的文本不在链接中.现在,找到所有URL,将其转换为<a>标记,然后将其替换为DOM:

Load up the string as HTML in ta DOM parser, iterate over the text nodes, and check for a URL. Make sure the text node's parent isn't an <a> tag, so you know that the text you're getting is not already in a link. Now, find all of the URLs, convert them to <a> tags, and replace them in the DOM:

$doc = new DOMDocument();
$doc->loadHTML( $str);

$xpath = new DOMXpath($doc);
foreach( $xpath->query('//text()') as $text) {
    if( !($text->parentNode->tagName == "a")) {
        $frag = $doc->createDocumentFragment();
        $frag->appendXML( preg_replace('#(http://stackoverflow.com/)#', '<a href="$1">$1</a>', $text->data));
        $text->parentNode->replaceChild( $frag, $text);
    }
}

请注意,这依赖于正则表达式来标识URL,这是一项艰巨的任务.我建议您找到一种适合您需求的产品,因为它目前正在使用:

Note that this relies on a regex to identify URLs, which is a difficult task. I suggest finding one that suits your needs, as it is currently using:

#(http://stackoverflow.com/)#

但是,鉴于此输入:

http://stackoverflow.com/ is a wonderful URL.

<a href="http://stackoverflow.com/">Has already been linked.</a>

<a href="http://stackoverflow.com/">http://stackoverflow.com/</a>

产生此输出:

<p><a href="http://stackoverflow.com/">http://stackoverflow.com/</a> is a wonderful URL. 

<a href="http://stackoverflow.com/">Has already been linked.</a> 

<a href="http://stackoverflow.com/">http://stackoverflow.com/</a></p>

这篇关于PHP自动链接(如果尚未链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆