Forum Moderators: coopster & phranque

Message Too Old, No Replies

how to convert URLs into links?

how can I do to convert url's which are in a string into their links?

         

webguide

11:09 pm on Jun 17, 2002 (gmt 0)



Hi All,
how can I do with PHP to capture and create links in a string?
e.g. to convert the following string:

"My favorite web-site is www.altavista.com but also [google.com...]
morever you can write me at pippo@pippo.pp and so on"

into

"My favorite web-site is <A HREF='www.altavista.com'>www.altavista.com</A>
but also <A HREF='http://google.com'>http://google.com</A> morever you can
write me at <A HREF='mailto:pippo@pippo.pp'>pippo@pippo.pp</A> and so on"

Thanks in advance

DrDoc

5:16 am on Jun 18, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, and welcome to WebMaster World!

You have to do this with regular expressions. Not too hard actually, if you know how to do it.

Say that the text is in the var $myVar. Then, all you have to do is add this line:

For PHP:

preg_replace("'http://[^\s]+[a-z0-9\/\.]'ei", \\1?"<a href=\"\\1\" target=\"_blank\">\\1</a>":"", $myVar);

For Perl:
$myVar =~ s'http://[^\s]+[a-z0-9\/\.]'$&?"<a href=\"$&\" target=\"_blank\">$&</a>":""'eig;

Not entirely sure about the PHP one, but I think it will work .. What is equivalent to Perl's $&?

DrDoc

5:22 am on Jun 18, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$myVar = preg_replace("/\b((http(s?):\/\/)¦(www\.))([\w\.]+)([\/\w+\.]+)\b/i",
"<a href=\"http$3://$4$5$6\"
target=\"_blank\">$2$4$5$6</a>", $myVar);

webguide

8:23 am on Jun 18, 2002 (gmt 0)



I found the solution (PHP), here is the code:

function createlinks($strtoconvert) {
$strtoconvert = preg_replace("/((http(s?):\/\/)¦(www\.))([\w\.]+)/i", "<a href=\"http$3://$4$5\">$2$4$5</a>", $strtoconvert);
$strtoconvert = preg_replace("/([\w\.]+)(@)([\w\.]+)/i", "<a href=\"mailto:$0\">$0</a>", $strtoconvert);
echo $strtoconvert;
}