PHP 在字符串中查找 URL 并建立链接。如果尚未在链接中

jsb*_*jsb 5 php hyperlink preg-replace preg-match

我想在链接尚未在链接中的字符串中查找 URL

我当前的代码:

$text = "http://www.google.com is a great website. Visit <a href='http://www.google.com' >http://google.com</a>"
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";


if(preg_match($reg_exUrl, $text, $url)) {
   $links = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $_page['content']['external_links']);

}
Run Code Online (Sandbox Code Playgroud)

问题在于它返回了两次链接(这就是它返回的内容):

<a href="http://www.google.com" rel="nofollow">http://www.google.com</a> is a great website. Visit <a href='<a href="http://www.google.com" rel="nofollow">http://www.google.com</a>' ><a href="http://www.google.com" rel="nofollow">http://www.google.com</a></a>
Run Code Online (Sandbox Code Playgroud)

mik*_*e.k 0

我在这里假设您想要匹配的 URL 后面会跟有空格、标点符号,或者位于行尾。当然,如果有类似的情况<a href="site">http://url </a>,那就不太好办了。如果您预计会遇到这种情况,请首先将全部替换\s+</a></a>

$text = "http://www.google.com is a great website. Visit <a href='http://www.google.com' >http://google.com</a>, and so is ftp://ftp.theweb.com";
$reg_exUrl = "/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3})([\s.,;\?\!]|$)/";

if (preg_match_all($reg_exUrl, $text, $matches)) {
    foreach ($matches[0] as $i => $match) {
        $text = str_replace(
            $match,
            '<a href="'.$matches[1][$i].'" rel="nofollow">'.$matches[1][$i].'</a>'.$matches[3][$i],
            $text
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

http://www.google.com是一个很棒的网站。访问 http://www.google.com' > http://google.com ,ftp ://ftp.theweb.com也是如此