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

PHP在字符串中查找URL并创建链接。如果尚未在链接中,php,hyperlink,preg-replace,preg-match,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_m

我想在链接不在链接中的字符串中查找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']);

}
$text=”http://www.google.com 是一个很棒的网站。请访问“
$reg|u 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,,$_page['content']['external_links']);
}
问题是它返回链接两次(这是它返回的):

是一个很棒的网站。访问'>

我在这里假设您要匹配的URL后面会有空格、标点符号,或者在一行的末尾。当然,如果有类似于
的东西,那么它就不能很好地工作。如果您希望遇到这种情况,请首先将所有
\s+
替换为

$text=”http://www.google.com 是一个伟大的网站。访问,也是ftp://ftp.theweb.com";
$reg|U exUrl=“/((http | https | ftp | ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3})([\s,;\?\!]\$)/”;
if(preg_match_all($reg_exUrl,$text,$matches)){
foreach($i=>$match时匹配[0]{
$text=str\u替换(
$match,
''.$matches[3][$i],
$text
);
}
}
输出:


这是一个很棒的网站。参观http://www.google.com“>”,

如果您只想计算标记中不存在的链接,那么可以编辑您的正则表达式,以便检查您的链接是否没有被简单引号或双引号包围。这并不简单,因为url可以位于html文档中的多个位置(在href属性、src属性、DTD或javascript代码中)。因此,更好的方法是提取文档中不是链接节点(或脚本/样式节点)子节点的文本节点并进行替换。使用
preg\u replace\u callback
这不会将nofollow添加到已经是html的url中link@GillesMisslin我想我可以重新审视一下这个问题。你用了什么文本?这是一种错误的方式。
preg\u replace\u callback
是这里使用的正确函数。
<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>
$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
        );
    }
}