<< All Posts
Hashtag regex formatter in PHP


I have a personal url bookmarks online. I’m not going to tell you what’s the url because it’s personal. Even using password in this page, I’m not going o tell you. 😛

Let’s know how to create a regex detector and formatter for hashtags?

Let’s use CSS from bootstrap 2.3:

.label {
    border-radius: 3px;
.label, .badge {
    background-color: #333333;
    color: #FFFFFF;
    display: inline-block;
    font-size: 11.844px;
    font-weight: bold;
    line-height: 14px;
    padding: 2px 4px;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
    vertical-align: baseline;
    white-space: nowrap;
.label-inverse, .badge-inverse {
    background-color: #333333;

And here is our PHP code:

$string = "Please, format all my hashtags. #rodolfo, #rodolfo-bandeira, #testing";
$hashtag_formater = preg_replace("/(#[a-zA-Z-_]+)/",
                   "<span class=\"label label-inverse\">$1</span>",
echo $hashtag_formater;

<< All Posts


🇧🇷 🇨🇦
Runs on OpenBSD 🐡