Parsing hashtags in PHP

While building the latest version of our Los Pulse app, I've found that we've written some code that could be pretty useful for all you Googlers out there.

If you've ever worked with the Twitter or Instagram APIs, you'll undoubtedly come across instances where you'll need to link a hashtag within some text.

Here's how we're doing it:

$tweet = preg_replace("/#(\w+)/", "<a href='$1' target='_blank'>#$1</a>", $tweet);

Outputting is simple enough, but what if we want to actually parse & store the hashtags.

Well, that's easy, too. Here's a quick little method to parse all the hashtags in a string:

 * Method to parse and store hashtags
 * @param	string			hashtag
 * @return	boolean
 * @since	2.3
private function parseHashtags($text) {

	//Create an array to store that hashtags
	$hashtags = array();
	//Match all the hashtags
	preg_match_all("/(#\w+)/", $text, $matches);
	//Check if we have matches then do something with it
	if( !empty($matches[0]) ){
		foreach( $matches[0] as $hashtag ){
			//"Clean" the hashtag by removing the '#'
			//Let's also make it lowercase for some consistency
			$hashtag = strtolower( str_replace('#', '', $hashtag) );
			//Here is where you'll want to store the hashtag
			//Typically we do a check to see if it exists
			$hashtag_id = methodThatChecksIfHashTagExists($hashtag);
			//If the hashtag doesn't exist, let's create it
			if( !isset($hashtag_id) ){
				$hashtag_id = methodThatCreatesTheHashtag($hashtag);
			//Now that we have the hashtag_id, we can do something with it
			//Hint: You may want to add the (comment-hashtag) relationship to the item here.		


We use the above method for parsing hashtags in photo submission captions as well as in comments.

If you're looking to add hashtagging functionality into your app, hopefully you find this little blog post useful!

sharing link :
category : Development