views:

148

answers:

1

I found a function online for turning a url within a string into a clickable link. However, when the url contains a hashtag it doesn't work. eg. http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759

Here's the part of the function concerned:

$ret = preg_replace(
    "#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#",
    "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>",
    $ret
);

$ret = preg_replace(
    "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#",
    "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>",
    $ret
);

Any ideas? thanks

A: 

Try this:

<?php

$text = "This is my link:  http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759";
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" target=\"_blank\">\\0</a>", $text); 
echo $text; // output: This is my link:  <a href="http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759" target="_blank">http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759&lt;/a&gt;

?>
Simone Vellei