Find and Replace Hashtags and Mentions in PHP

Social network messages often use hashtags and username mentions to build connections. For example, following message mentions username such as @dummyuser and has hashtags such as #dummytag.

A dummy message mentioning @dummyuser and @dummyuser0, 
and tagged with #dummytag and #dummytag0

The following examples show how to retrieve and replace hashtags and mentions using regular expressions in PHP.

Find All Hashtags and Mentions

The following code uses preg_match_all to retrieve all hashtags or usernames into an array.

$msg = "A dummy message mentioning @dummyuser and @dummyuser0,".
       " and tagged with #dummytag and #dummytag0";
preg_match_all('/(#\w+)/', $msg, $matches);
foreach ($matches[0] as $hashtag)
	echo $hashtag . ' ';

preg_match_all("/(@\w+)/", $msg, $matches);
foreach ($matches[0] as $username)
	echo $username . ' ';

The output is as follows.

#dummytag #dummytag0 @dummyuser @dummyuser0

The function preg_match_all performs a global regular expression match. It searches subject for all matches to the regular expression given in pattern and puts them in matches.

int preg_match_all ( string $pattern , string $subject, 
                     array &$matches )

Note that $matches[0] is an array of full pattern matches. Details can be found from the official document: preg_match_all.

Replace Hashtags and Mentions by HTML Code

The following code uses preg_replace to replace all hashtags or usernames by links to relevant pages.

$new_msg = preg_replace('/#(\w+)/', 
                    '<a href="http://example.com/tag/$1">#$1</a>', 
                    $msg);
echo $new_msg;
$new_msg = preg_replace('/@(\w+)/',  
                    '<a href="http://example.com/user/$1">@$1</a>', 
                    $msg);
echo $new_msg;

Using indexed arrays, the following code replaces both hashtags and usernames.

$pat = array('/#(\w+)/', '/@(\w+)/');
$rep = array('<a href="http://example.com/tag/$1">#$1</a>', 
             '<a href="http://example.com/user/$1">@$1</a>');
$new_msg = preg_replace($pat, $rep, $msg);

The function preg_replace performs a regular expression search and replace. It searches subject for matches to pattern and replaces them with replacement.

mixed preg_replace ( mixed $pattern , mixed $replacement , 
                     mixed $subject )

Details can be found from the official document: preg_replace.

Comments

comments