Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract hashtag content?

Tags:

regex

php

I am trying to extract the content following a hashtag using php.

For example:

$sentence = 'This #Coffee is the #best!!';

How do I get the value 'Coffee' and 'best'? Note, I don't want the exclamation mark after 'best'

like image 964
anna Avatar asked Nov 04 '10 20:11

anna


People also ask

How do you split words in a hashtag?

The different words of a hashtag should be distinguished by using capital letters. For instance, a very popular hashtag campaign by Red Bull #PutACanOnIt is basically “Put a can on it.” The use of capital letters makes it easier to distinguish the different words of a hashtag.

How do you search using hashtags?

You can also: Search for a hashtag using Facebook's search bar. Click on a hashtag to see a feed of Facebook posts using that same hashtag. Search hashtags used in private Facebook groups using the “search this group” bar under the group's menu.


2 Answers

A pretty safe catch-all in utf-8/unicode:

preg_match_all('/#([\p{L}\p{Mn}]+)/u',$string,$matches);
var_dump($matches);

Although, if you're not using / expecting exotic characters, this might work equally well and is more readable:

preg_match_all('/#(\w+)/',$string,$matches);
like image 76
Wrikken Avatar answered Sep 28 '22 12:09

Wrikken


Try this one:

|\#(\w*)|

Run in a sentence like

I want to get all #something with #this

It will retrieve "something" and "this". Im assuming that you only wanted the Regex, the function to use is preg_match_all

like image 42
David Conde Avatar answered Sep 28 '22 14:09

David Conde