If you are not aware of Hashtag, then I will say you would not using any social networking sites in a very large extent. Here I am going to explain you about the advantages of hashtag & how you can implement it in your web projects using php & mysql.
Please check my popular article on Facebook / Twitter Style Mention System with PHP, MYSQL & jQuery
Contents
What is Hashtag & Why do we use Hashtag?
Hashtags are essentially a filter, allowing people to see the conversation associated with that word or phrase. Hashtags is alternative to tags.. Twitter is the first site to introduce the hashtag. But now a days sites like facebook, Instagram, Vine & Tumblr are using this feature in all platforms. If you use the hashtag effectively then you will get the contents across different sites together in a single page.
Checkout my latest article on How to find @mention in a string using PHP regrex
Database Design
To create Facebook Like Hashtag System , You need to create one table called “Messages”
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`message` text COLLATE utf8_unicode_ci NOT NULL,
`hashtag` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Data will be stored like this
Php Code to Filter Hashtag from Text
Below php code is used to filter the hashtag (#text) from any paragraphs in your web applications. You need to call the function called <ins>gethashtags($text)</ins> with parameter as texts.
function gethashtags($text)
{
//Match the hashtags
preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $text, $matchedHashtags);
$hashtag = '';
// For each hashtag, strip all characters but alpha numeric
if(!empty($matchedHashtags[0])) {
foreach($matchedHashtags[0] as $match) {
$hashtag .= preg_replace("/[^a-z0-9]+/i", "", $match).',';
}
}
//to remove last comma in a string
return rtrim($hashtag, ',');
}
//usage
$text = "w3lessons.info - #php programming blog, #facebook wall script";
echo gethashtags($text); //output - php,facebook
We need to convert hashtags into clickable links. Here is the simple php function that will convert #hashtag, @mentions & normal http, https links into clickable links
function convert_clickable_links($message)
{
$parsedMessage = preg_replace(array('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i'), array('<a href="$1" target="_blank">$1</a>', '$1<a href="">@$2</a>', '$1<a href="index.php?hashtag=$2">#$2</a>'), $message);
return $parsedMessage;
}
Here config.php contains the information about database settings and functions.php contains gethashtags & convert_clickable_links functions
if(isset($_POST['msg']) && $_POST['msg'] != '')
{
require_once 'config.php';
require_once 'functions.php';
$message = strip_tags(trim($_POST['msg']));
//get hashtag from message
$hashtag = gethashtags($message);
//insert into messages table
$query = mysql_query("INSERT INTO `messages` (`message`, `hashtag`) VALUES ('$message', '$hashtag')") or die(mysql_error());
$ins_id = mysql_insert_id();
?>
<div class="msg_body" id="<?php echo $ins_id;?>">
<div class="msg_img">
<img src="http://0.gravatar.com/avatar/82620dd66b22b34a915303b93b92929b" />
</div>
<div class="msg_text">
<?php echo convert_links($message); ?>
<div class="time">5 seconds ago</div>
</div>
</div>
<?php
mysql_close();
}
index.php
If the hashtag parameter is present in the url, then I will filter the messages for corresponding hashtag. If not then I will list all the messages
if(isset($_GET['hashtag']) && $_GET['hashtag'] != '') {
$tags = trim($_GET['hashtag']);
$result = mysql_query("SELECT * FROM `messages` WHERE hashtag LIKE '%$tags%' ORDER BY `id` DESC");
$title = "Search results for <font color='red'>".$tags."</font> <a href='index.php'>clear</a>";
} else {
$result = mysql_query("SELECT * FROM `messages` ORDER BY `id` DESC");
$title = "Updates";
}
?>
<h3><?php echo $title; ?></h3>
<div id="updates">
<?php
$total_rows = mysql_num_rows($result);
if($total_rows > 0) {
while($row = mysql_fetch_array($result)) {?>
<div class="msg_body" id="message<?php echo $row['id'];?>">
<div class="msg_img"> <img src="https://0.gravatar.com/avatar/82620dd66b22b34a915303b93b92929b" /> </div>
<div class="msg_text"> <?php echo convert_links($row['message']);?>
<div class="time"><?php echo $row['time'];?></div>
</div>
</div>
<?php } }
</div>
jQuery Code
function updatedata() {
//preloader
$('#post-loader').show();
var msg = $("#message").val();
if(msg != '') {
$.ajax({
type: "POST",
url: "update.php",
data: 'msg='+msg,
cache: false,
success: function(html) {
$('#updates').prepend(html);
$('#post-loader').hide();
$("#message").val('');
},
error: function() {
$('#post-loader').hide();
}
});
return false;
} else {
alert("Message cannot be empty!");
return false;
}
}
Facebook Like Status Update Form
<div class="msg-container">
<div class="msg-form-content">
<div class="msg-form-header"> Update Status
<div class="msg-loader" id="post-loader" style="display:none"><img src="loading.gif" /></div>
</div>
<form id="form" name="form" action="" method="POST" >
<div class="msg-form-inner">
<textarea id="message" class="message-form" placeholder="What's on your mind?" name="message"></textarea>
</div>
<div type="button" name="action" class="msg-btn" value="Post"><a onclick="updatedata()" class="uibutton large confirm">Post</a></div>
</form>
</div>
</div>
If you find this tutorial useful, please share it with your friends and in social networks.
Your suggestions/comments are most welcome
i checked your facebook-style-hashtag-system and php-mention-system both are working good for hashtag system. but my concern is if i want both functionality in one code how can i integrate.
facebook-style-hashtag-system : it showing #tag and linking for hashtag and we can add new hashtags. but it doesn’t have autofill selection
php-mention-system: it have autofill selection from database but don’t have create new hashtags. here we can use only tags from database. if user wants to enter new hashtag it won’t allowing
please help me to sort or integrate these two options.
I registered as new users subscribe but now 24h later I getting this: Email does not exist in our database.
I would like to download the script ????
mysqli? its ridiculous stop using mysql its PDO OR MYSQLI GET TO 2017 WE ARE NO LONGER IN 2015
I agree. Move to PDO, please!
livemail.awadhesh@gmail.com unable to download, plz update ur db
I can’t download it.
Please accept my subscription, i am still waiting.
I can’t download it. I have been subscribe for 2 days ago.
please support update my email vubactest1@gmail.com. I just submit subscribed. Thank you so much.
Please check now. I have updated the database..
Thanks
I need to get this script more faster than 10 hours. Can you please send it to my mail:
avramoski123@gmail.com
Thanks
Function is “convert_clickable_links” but U R using convert_links in index.php & update.php
LINE 18 :
hi please update email database .
i can’t download .
Wow, an incredible easy to use PHP code, thanks 🙂
It will help me to create my little social network 😉
Cannot Download even after Subscribing…Can you please update the subscribers database
Cannot download
can’t download after I subscribe , it’s said Email does not exist in our database. Please use below form to subscribe
same here
sorry, but the database has a large fault…
you will need 3 tables, if you want to follow the normal forms…
1. `messages`
2. `hashtags`
3. `message_hashtags`
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`message` text COLLATE utf8_unicode_ci NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `hashtags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hashtag` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `message_hashtags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`messageId` int(11) NOT NULL,
`hashtagId` int(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX (`messageId`),
CONSTRAINT
FOREIGN KEY (`messageId`)
REFERENCES `messages` (`id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
INDEX (`hashtagId`),
CONSTRAINT
FOREIGN KEY (`hashtagId`)
REFERENCES `hashtags` (`id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Hi etenzy,
This tutorial is just an example… When we are building large applications, then your DB structure is the best.. I agree with you overall..
Thanks
can’t download after I subscribe , it’s said Email does not exist in our database. Please use below form to subscribe
the email will be update after 10 hours..so try after 10 hrs after subscibing
HI Nishant, Subscribers database has been updated.. pls download it now
thanks 😉