提取文本中的网址


Extract urls in text

假设我们的文本中包含多个 url,所以我想提取该 url 并进行一些更改,然后显示文本。

这是我正在使用的代码

<?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]那么我如何申请在文本中找到的所有链接~谢谢

您可以使用

preg_match_all(...),它返回一个匹配数组。然后循环访问结果($matches)并替换找到的实例。

更改下一行

$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);