PHP preg_replace多个url链接

时间:2014-05-07 15:58:44

标签: php regex preg-replace preg-match

我使用此代码将网址更改为链接:

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

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com http://www.ynet.co.il";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

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

} else {

       // if no urls in the text just return the text
       echo $text;

}
?>

但是每个链接指向第一个链接我如何制作解决它的foreach?

感谢。

Haim的

1 个答案:

答案 0 :(得分:2)

尝试:

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

更简单;)