Creating hashtag hyperlinks on the fly for your website
In this post I am going to show you how to take any string of text containing hashtags and convert them into clickable URLs, AKA "hyperlinks".
Okay, to get started we will first need some text containing hashtags.
$text = 'You can find #programming help at my #blog.';
Now we will use the following regular expression pattern to find all hashed words in the string.
$pattern = "/\#([A-Za-z0-9_-]*)/is";
It's important to note, that with this pattern, if you include anything inside the brackets, like a period after the 9, it will find the period with the word.
$text = preg_replace_callback($pattern,
function($matches){
$nohash = str_ireplace('#','',$matches[0]);
return '<a href="?tag='.$nohash.'" target="_self">#'.$matches[1].'</a>';
},
$text);
Be sure to replace the ?tag= inside the href attribute above to where you want the link to go.
Lastly we can echo out the results of the converted text.
echo text;
Comments
Post a Comment