DH
1 min read

Hashtags in PHP

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

php

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.

<?php

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.

<?php

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.

Damian Hodgkiss

Damian Hodgkiss

Senior Staff Engineer at Sumo Group, leading development of AppSumo marketplace. Technical solopreneur with 25+ years of experience building SaaS products.

Creating Freedom

Join me on the journey from engineer to solopreneur. Learn how to build profitable SaaS products while keeping your technical edge.

    Proven strategies

    Learn the counterintuitive ways to find and validate SaaS ideas

    Technical insights

    From choosing tech stacks to building your MVP efficiently

    Founder mindset

    Transform from engineer to entrepreneur with practical steps