Hashtags in PHP

How to generate hashtags from slugs and automatically link hashtags from text.


Working on a project today I had a few tasks to accomplish in PHP, specifically WordPress which I love to use for side-project sites due to its flexibility.

Even though I’m not a fan of its code quality, I do admire how easy it is to do basically anything and customize anything with the use of filters and actions.

So first up I needed to convert a plain text string into a hashtag. For example, “Make America Great Again” should become #makeamericagreatagain.


function str_to_hashtag($str) {
  // first we lower case
  $str = strtolower($str);

  // now remove anything not a number or alphabet character
  $str = preg_replace('/[^\da-z]/i', '', $str);
  return $str;

$tag = str_to_hashtag('Make America Great Again');

Next up, if we wanted to automatically hyperlink any hashtags in a paragraph to Twitter searches.


function link_hashtags($content, $tagUrl) {
  $content = preg_replace('/#([\da-z]+)/i', sprintf('<a href="%s">#$1</a>', $tagUrl), $content);

  return $content;

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tristique fermentum sem, sed tincidunt lectus venenatis id. Donec eu sapien. #merrychristmas #happynewyear';

$text = link_hashtags($text, 'https://twitter.com/hashtag/$1');

Two simple, but effective functions.