A hashtag is a word or an unspaced phrase or word prefixed with the hash symbol (#) that is used on various social websites to create (often distinct) social search terms that group various types of users and data (often collating data from various platforms). By clicking on a hashtag (essentially just a search term), you'll be connected with other people that are engaging on the same topic.
At least a few sites we've involved ourselves with lately utilise hashtags in one way or another. This post will show you how to extract hashtags from a string of text (using a basic function) and return the result as either an array or string of text.
Return Hashtag Array
The first function returns an array with all hashtags.
Consider the following sentence: "The quick brown #fox jumped over the lazy #fat#dog".
The keywords of
dog are our search terms with #fat#dog illustrating the 'unspaced' erroneous use of hashtags.
Using our PHP function we'll return the following array:
Return Hashtag String
To return the hashtags in a string, use the following:
fox, fat, dog.
Automatically Link Hashtag Words in a Sentence to Search
If you wanted to return the original string of text (not just the hash terms) with hashtag characters linked to a search form, you could use something similar to the following:
- Hashtags should only include alphanumeric characters and underscores. The regular expression
'/#(\w+)/'excludes anything other than these characters. The lowercase
wmatches any alpha numeric character including underscore (_) (while the uppercase
Wwill match any non alpha numeric character excluding the underscore character). A common error on social platforms is to include these illegal characters meaning that the hashtag breaks and loses any significance (you'll often see people incorrectly use apostrophes in hastags).
- Some social platforms won't permit hashtags that include only numbers... or tags that start with numbers. You may need to alter the expression to suit a particular platform you're trying to emulate.
- An article scheduled here will show you how to automatically create hashtags from text. It emulates features used by Google+ and others.