I have the following string:
"Look on http://www.google.com".
I need to convert it to:
"Look on http://www.google.com"
The original string can have more than 1 URL string.
How do I do this in php?
Thanks
I have the following string:
"Look on http://www.google.com".
I need to convert it to:
"Look on http://www.google.com"
The original string can have more than 1 URL string.
How do I do this in php?
Thanks
How about this:
$string = "Look on http://www.google.com"
$new_string = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $string);
(I found that here, btw).
Ben
You will need to use regular expressions...
Something like this will help.
$result = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/i', '<a href="\0">\0</a>', $text);
Have a look at regular expressions. You would then do something like:
$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
lib_autolink
does a pretty good job, avoiding pitfalls like extra punctuation after the link and links inside HTML tags:
I found an example which allows for links that include ftp, https and others which seems to work fine for multiple URLs
how-to-detect-urls-in-text-and-convert-to-html-links-php-using-regular-expressions
<?php
// The Regular Expression filter
$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
//example text
$text="Example user text with a URL http://www.zero7web.com , second link http://www.didsburydesign.co.uk";
// convert URLs into Links
$text= preg_replace($pattern, "<a href=\"\\0\" rel=\"nofollow\">\\0</a>", $text);
echo $text;
?>
Proabably a good idea to add nofollow to the link too is it's a user submitted value.
Try this...
<?
function link_it($text)
{
$text= preg_replace("/(^|[\n ])([\w]*?)([\w]*?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text);
$text= preg_replace("/(^|[\n ])([\w]*?)((www)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text);
$text= preg_replace("/(^|[\n ])([\w]*?)((ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"ftp://$3\" >$3</a>", $text);
$text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);
return($text);
}
$text = "ini link gue: http://sapua.com <br>
https://sapua.com <br>
anything1://www.sss.com <br>
dua www.google.com <br>
tiga http://www.google.com <br>
ftp.sapua.com <br>
[email protected]
";
print link_it($text);
?>