【问题标题】:Get hashtags from string, replace some symbols in it and convert it to link PHP从字符串中获取主题标签,替换其中的一些符号并将其转换为链接 PHP
【发布时间】:2014-02-05 09:48:35
【问题描述】:

我有一些带有标签的字符串,看起来像@user_name。 现在我以这种方式将所有主题标签转换为链接:

$text = preg_replace ("/@(\\w+)/", '<a href="http://$1.'.SITE_NAME.'">@$1</a> ', $text);

如您所见,所有主题标签都变成了子域名。如果您知道,子域名中的_ 符号存在一些问题(某些浏览器不支持,IE 支持,但未设置cookie 等)。所以我需要将子域中的_ 符号替换为-(减号),但在标签视图中保留_ 符号。将我需要的内容链接到&lt;a href="http://user-name.site.com"&gt;@user_name&lt;/a&gt;。怎么样?

【问题讨论】:

  • 哈希标签是#。当然你的意思是at 符号 (@)
  • @BeatAlex 我认为在这种情况下没关系
  • 嗯,不,无论是# 还是@,它仍然可行,但你要求的是一个标签,这是我感到困惑的地方,因为没有'您的代码中没有任何内容。
  • @BeatAlex 也许你会觉得很奇怪,但在苏联俄罗斯,我们将文本中的 # 和 @ 标签都称为“hashtags”。 =)

标签: php regex preg-replace str-replace hashtag


【解决方案1】:

你可以像这样使用 preg_replace_callback():

$text = preg_replace_callback ("/@(\\w+)/", function ($matches) {
    return '<a href="http://'. str_replace('_', '-', $matches[1]) .'.abc.com.">'.$matches[1].'</a> '; },  "test @user_john here");

【讨论】:

  • 谢谢!现在我知道了新的 php 函数。
【解决方案2】:

嗯,看来你已经有了答案……

我打算建议使用这个正则表达式:

(https?:..[^\.]*)(_)([^\.]*)

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多