Web / PHP

PHP function for Hashtags

by Libz
20 Jul 2017 at 07:10hrs | 2237 Views
This PHP function can automatically add hyper links to hashtags.

The function uses php's preg_replace function, which perform a regular expression search and replaces all word that have the # character with the same characters linked to an appropriate hashtag search page.

  1. The function takes in two string arguments, the first argument is a string, which might contain hashtag/s e.g. the body of a blog post.
  2. The second argument is the base hashtag url.
The function outputs a string with, if input string had hashtags, they will be hyper linked.

function hashtag($string,$url){
$string = preg_replace( '/(\#([a-zA-Z0-9\-_]+))/i', "<a href=\"$url\2\">\0</a>", $string);
return $string;

Function in action

//Input string
$inputString = 'This is just sample text for #testing hashtags'

//Url to hashtag search page
$url = 'http://mydomain.com/search.php?hashtag='

echo hashtag($intring,$url)

The above will output the following HTML:

This is just sample text for <a href="http://mydomain.com/search.php?hashtag=testing">#testing</a> hashtags

Source - Accessing Code
More on: Hashtag system

Chat Login

Register | Forgot password