I've been searching around for this but all I could find was broken scripts and plus, I might have a method that is quite simple.
I'm trying to use a for () loop for this one.
This is what I've got:
<?php
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$makerepstring = "Here is a link: http://youtube.com and another: http://google.com";
if(preg_match_all($reg_exUrl, $makerepstring, $url)) {
// make the url into link
for($i=0; $i < count(array_keys($url[0])); $i++){
$makerepstring = preg_replace($reg_exUrl, '<a href="'.$url[0][$i].'" target="_blank" rel="nofollow">'.$url[0][$i].'</a> ', $makerepstring);
}
}
echo $makerepstring;
?>
However this fails brutally for some reason I can't comprehend.
The output from echo $makerepstring;
as follows(from source code):
<a href="<a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a> " target="_blank" rel="nofollow"><a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a> </a> <a href="<a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a> " target="_blank" rel="nofollow"><a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a> </a>
I'd really like to do it with a for()... Could somebody try and figure out how to get this to work with me?
Thanks in advance!
/J
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$makerepstring = "http://youtube.com http://google.com";
$url = array();
$instances = preg_match_all($reg_exUrl, $makerepstring, $url);
if ($instances > 0) {
// make the url into link
for($i=0; $i < count(array_keys($url[0])); $i++){
$makerepstring = preg_replace($reg_exUrl, '<a href="'.$url[0][$i].'" target="_blank" rel="nofollow">'.$url[0][$i].'</a> ', $makerepstring);
/*echo $url[0][$i]."<br />";
echo $i."<br />";
print_r($url);
echo "<br />";*/
}
}
echo $makerepstring;
This does not work either, although I'm not quite sure how you meant I should do this.
EDIT:
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$makeurl = "http://google.com http://youtube.com";
if(preg_match($reg_exUrl, $makeurl, $url)) {
echo preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank" rel="nofollow">'.$url[0].'</a> ', $makeurl);
} else {
echo $makeurl;
}
Would give:
<a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a> <a href="http://google.com" target="_blank" rel="nofollow">http://google.com</a>