2010-04-14 34 views
0

我在線找到了將字符串中的url轉換爲可單擊鏈接的功能。但是,當網址包含哈希標籤時,它不起作用。例如。 http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759當url包含主題標籤時,如何獲得preg替換工作

這裏的功能有關的部分:

$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 
); 

任何想法?感謝

+0

其中的這部分失敗了,你呢?據我所知,它適用於[我的設置](http://static.bwerp.net/~adam/2010/04/14/r.php)。 – 2010-04-14 19:36:22

+0

它結束爲:#gallery5759「target =」_blank「> http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759 – Steven 2010-04-14 19:38:22

+0

@ Adam - 任何想法爲什麼它適合你但不適合我? – Steven 2010-04-14 19:44:23

回答

0

試試這個:

<?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</a> 

?>