【问题标题】:Regular expression to find and replace @ mentions like twitter正则表达式查找和替换 @ 提及,如 twitter
【发布时间】:2011-07-13 04:04:09
【问题描述】:

我正在开发一个 PHP 应用程序,它需要一个正则表达式来替换 @ 提及,如 twitter。此外,正则表达式应满足以下需求。

  1. 如果只有@ 并且之前和之后都没有,则不应替换它。
  2. 不应替换电子邮件中的@。例如。 sam@example.com 不应被替换。
  3. 只有@sam@example 之类的字符串应替换为<a href="http://twitter.com/sam">@sam</a><a href="http://twitter.com/example">@example</a>

请帮忙。提前致谢。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    哇。我自己找到了答案。

    $tweet = preg_replace('/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '$1<a href="http://twitter.com/$2">@$2</a>', $tweet);
    

    感谢你们的帮助。

    【讨论】:

      【解决方案2】:

      怎么样 -

      (?<!\w)@[\w]+
      

      【讨论】:

        【解决方案3】:

        由于 twitter 最多可以包含 15 个字符,你可以这样写以避免一些错误:

        $tweet = preg_replace("/(^\w)@(\w{1,15})/i", "\\1<a ref=\"http://twitter.com/\\2\">@\\2</a>", $tweet);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-25
          • 2011-06-16
          • 1970-01-01
          • 2017-01-28
          • 2015-01-11
          • 2012-12-02
          • 1970-01-01
          相关资源
          最近更新 更多