将哈希标签制作成链接,而不会破坏使用哈希符号的链接


Making hash tags into links without ruining links that use the hash symbol

我有一个帖子系统,我希望同时支持链接和哈希标签。问题是某些链接本身包含#,并且代码尝试将链接中的#转换为更多链接!

用户可能会发布"http://somelink.com#hashKeyword #hashtag

这是我正在使用的代码。我相信它有效,除了链接包含主题标签时。

$theText = "http://somelink.com#hashKeyword #hashtag";
//Convert links
$reg_exUrl = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
if(preg_match($reg_exUrl, $theText, $url)) {
   $theText = preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a>', $theText);
}
//Convert hash tags
$theText = preg_replace("/#('w+)/", '<a href="linktohashtag/#$1">#$1</span>', $theText);

任何帮助将不胜感激!

通过使用HamZa的评论和对这个问题的回答,我能够解决这个问题。

我只是简单地格式化了主题标签正则表达式,以仅查找空格或帖子开头之后的标签。这样,它们就不会与正常链接冲突。

/(^|'s)#([A-Za-z_][A-Za-z0-9_]*)/

这是新的最后一行代码:

$theText = preg_replace("/(^|'s)#([A-Za-z_][A-Za-z0-9_]*)/", '$1<a href="linktohashtag/#$2">#$2</span>', $theText);

效果很好!谢谢大家的讨论!

听起来你试图用一个公式得到两个不同的结果,即 X = 1,X = 2......但是 X 不能同时等于 1 和 2。您需要做出选择并实施不同的东西。

通常,URL 中的#会尝试在 HTML dom 中查找包含匹配 id 属性的元素。因此,http://www.example.com/index.php#who-are-we将打开索引页,然后将浏览器视图切换到元素<h1 id="who-are-we">。这可以是任何 HTML 元素,我只是在这个例子中使用了 h1。

关于在您的网站上创建链接,您可能希望创建一个脚本来解析它们,使它们对 URL 友好。因此,如果帖子标题是 How to work with twitter #hashtags ,您的脚本将用连字符替换空格,并去除所有非字母数字或空格。所以你会得到一个像 how-to-work-with-twitter-hashtags .