and like us on FB

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 fox, fat and 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:

Returns: 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:

Example Usage:

Returns: This is a test using the hashtags of #WordPress and #Shortcode.


  • Hashtags should only include alphanumeric characters and underscores. The regular expression '/#(\w+)/' excludes anything other than these characters. The lowercase w matches any alpha numeric character including underscore (_) (while the uppercase W will 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.


Title: Extract #Hashtag Keywords from a String of Text with PHP
Description: Extract #Hashtag Keywords from a String of Text with PHP. Includes three PHP functions.
Download: PHP Code (V0.2) | Plugin Page

Shortt URL for this post: