在文本中提取网址

时间:2012-05-11 18:18:54

标签: php

假设我们的文本中包含多个网址,因此我想提取该网址并进行一些更改,然后显示文字。

这是我正在使用的代码

<?PHP
$text = "This is text with links http://google.com and www.yahoo.com";

$text = ereg_replace( "www\.", "http://www.", $text );
$text = ereg_replace( "http://http://www\.", "http://www.", $text );
$text = ereg_replace( "https://http://www\.", "https://www.", $text );

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

if(preg_match($reg_exUrl, $text, $url)) {

$text = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
echo $text;

}else{

echo "NO URLS";

}
?>

问题

//输出源(重复第一个链接)

This is text with links <a href="http://google.com" rel="nofollow">http://google.com</a> and <a href="http://google.com" rel="nofollow">http://google.com</a>

它取决于数组所以它只需要第一个URL $url[0]所以如何申请在文本中找到所有链接〜谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用preg_match_all(...),它会返回一系列匹配项。然后循环结果($matches)并替换找到的结果。

答案 1 :(得分:0)

更改下一行

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$reg_exUrl = "/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/";

$text = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);

$text = preg_replace($reg_exUrl, '<a href="\1" rel="nofollow">\1</a>', $text);
相关问题