Regular expression to find and replace @ mentions like twitter

后端 未结 3 661
一生所求
一生所求 2020-12-18 16:00

I am developing a PHP application which needs a regular expression to replace the @ mentions like twitter. Also the regular expression should satisfy the following needs.

相关标签:
3条回答
  • 2020-12-18 16:22

    How about something like -

    (?<!\w)@[\w]+
    
    0 讨论(0)
  • 2020-12-18 16:28

    Wow. I found the answer myself guys.

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

    Thanks for your help guys.

    0 讨论(0)
  • 2020-12-18 16:36

    As twitter can contain up to 15 characters, you could write it like this to avoid some bugs:

    $tweet = preg_replace("/(^\w)@(\w{1,15})/i", "\\1<a ref=\"http://twitter.com/\\2\">@\\2</a>", $tweet);
    
    0 讨论(0)
提交回复
热议问题