当url包含主题标签时,如何让preg替换为work

时间:2010-04-14 19:27:43

标签: php preg-replace pcre

我发现了一个在线功能,可以将字符串中的网址转换为可点击的链接。但是,当url包含主题标签时,它不起作用。例如。 http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759

以下是相关功能的一部分:

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

有什么想法吗?感谢

1 个答案:

答案 0 :(得分: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>

?>