I'm trying to set up a hashtag system in PHP, where if the user input contains a #
next to a word, it will be replaced with a link.
For example:
$input = "mysql_real_escape_string($_POST['input'])";
$sql = "INSERT INTO table (input) VALUES ('$input')";
mysql_query($sql, $connect);
?>
<?php
mysql_select_db("database",$connect);
$sql = mysql_real_escape_string("SELECT * FROM input");
$myData = mysql_query($sql, $connect);
echo $myData;
where $myData
says something like "Just went 80mph in a schoolzone #yolo"
I want it to echo out:
Just went 80mph in a schoolzone <a href="search?q=%23yolo">#yolo</a>
like on Twitter. I don't know how to set this up, but I assume preg_match()
or str_replace()
may be involved.
The regex you're looking for is #([^\s]+)
which matches one or more characters after a hash until white-space occurs. This can then be used with a preg_replace to create a link.
E.g.
$output = preg_replace( "/#([^\s]+)/", "<a href=\"search?q=%23$1\">#$1</a>", $input );