Regex to conditionally replace Twitter hashtags with hyperlinks

前端 未结 4 825
野的像风
野的像风 2020-12-05 16:49

I\'m writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a rege

4条回答
  •  庸人自扰
    2020-12-05 17:18

    (^|\s)#(\w*[a-zA-Z_]+\w*)
    

    PHP

    $strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#\2', $strTweet);
    

    This regular expression says a # followed by 0 or more characters [a-zA-Z0-9_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters.

    http://rubular.com/r/opNX6qC4sG <- test it here.

提交回复
热议问题