How to remove # from Twitter hashtags?

后端 未结 3 1134
渐次进展
渐次进展 2021-01-22 16:02

I want to strip off the # from twitter hash-tags, so:

Input: I love #winter and #ice-skating
Output: I love winter and ice-skating

I thought th

相关标签:
3条回答
  • 2021-01-22 16:16
    1. You need to have a sub-pattern to match the string without the pound sign
    2. Don't wrap 1 in the replacement string with curly braces
    $tweet = preg_replace('/#([^\s]*)/', '$1', $tweet);
    
    0 讨论(0)
  • 2021-01-22 16:26

    Faster solution:

    $tweet = str_replace('#', '', $tweet)
    

    No regex required

    0 讨论(0)
  • 2021-01-22 16:30

    You need to surround the part you want to capture in parentheses:

    $tweet = preg_replace('/#([\w-]+)/i', '$1', $tweet);
    

    See it working online: ideone

    I also changed the regular expression to be more specific, but for an even better regular expression I refer you to this question and its answers (for .NET but the idea is the same in PHP):

    • Best HashTag Regex
    0 讨论(0)
提交回复
热议问题