Regex to conditionally replace Twitter hashtags with hyperlinks

元气小坏坏 提交于 2019-11-27 20:50:15
Gazler
(^|\s)#(\w*[a-zA-Z_]+\w*)

PHP

$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $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.

It's actually better to search for characters that aren't allowed in a hashtag otherwise tags like "#Trentemøller" wont work.

The following works well for me...

preg_match('/([ ,.]+)/', $string, $matches);
Satya Prakash

I have devised this: /(^|\s)#([[:alnum:]])+/gi

steadweb

I found Gazlers answer to work, although the regex added a blank space at the beginning of the hashtag, so I removed the first part:

(^|\s)

This works perfectly for me now:

#(\w*[a-zA-Z_0-9]+\w*)

Example here: http://rubular.com/r/dS2QYZP45n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!