Hashtag System and Regex PHP Programming Tutorial
In this programming exercise you can learn how to create a PHP hashtag conversion system. It will convert any hashtags found in data strings to clickable links that lead to your dynamic hashtag rendering page. You can also get some great insight into how Regular Expression strings work as we construct a regular expression from scratch to perform the conversion.
example.php
<?php
function convertHashtags($str){
$regex = "/#+([a-zA-Z0-9_]+)/";
$str = preg_replace($regex, '<a href="hashtag.php?tag=$1">$0</a>', $str);
return($str);
}
$string = "I am #UberSilly and #MegaPlayful online";
$string = convertHashtags($string);
echo $string;
?>
hashtag.php
<?php
if(isset($_GET["tag"])){
$tag = preg_replace('#[^a-z0-9_]#i', '', $_GET["tag"]);
// $tag is now sanitized and ready for database queries here
$fulltag = "#".$tag;
echo $fulltag;
}
?>