Hashtags in PHP

12/24/2018 — 1 min read

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.

Related Articles

Start Creating Freedom today

Learn to build fast, scalable SaaS as I document my journey towards freedom. Follow along for real-world lessons and insights from my experiences.

    No spam ever. Unsubscribe anytime.
    1.1K builders