【问题标题】:How do I get preg replace to work when the url contains a hashtag当 url 包含主题标签时,如何让 preg 替换工作
【发布时间】:2010-04-14 19:27:42
【问题描述】:

我在网上找到了一个函数,可以将字符串中的 url 转换为可点击的链接。但是,当 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
);

有什么想法吗?谢谢

【问题讨论】:

标签: php preg-replace pcre


【解决方案1】:

试试这个:

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

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2023-04-05
    相关资源
    最近更新 更多