AlbrightK AlbrightK - 1 year ago 65
PHP Question

Exploding Multiple Hashtags

I'm currently developing a lightweight internal messaging script for a local group, which utilises a custom made BBCode style parser, to translate forum style tags such as [b] into its HTML equivalent.

I've also been including a Twitter like hashtag feature, so people can tag and track discussions within the messaging system, which works well, until the user enters more than one hashtag into the text.

Typically the user would enter their text into the submission form as such.

Lorum Ipsum dolor sit amet, #consectetur adipiscing elit.

Using SQL, the discussion tracker loads the last 20 messages and loops through them, each time calling the TrackDiscussion($i); function. The $i parameter is where the text/submission is fed into to check for hashtags.

function TrackDiscussion($i,$str=1) {
$i = 0;
foreach($matches[1] as $match) {
$keywords .= "$match";
if ($count>$i) $keywords .= ", ";
foreach($matches[1] as $match) {
return $keywords;

This all works fine, until it finds more than one hashtag in the text, and instead of outputting:

<a href="">#hashtag1</a>, <a href="">#hashtag2</a>

It outputs:

<a href=",hashtag2">#hashtag1, #hashtag2</a>

I apologise the the messy code, but would I be right in surmising that I would need split the keywords apart, most likely by the explode function?

If anyone could give me a pointer as to where I would put that, I'd be more than grateful, I've been going over it time and time again and I can't seem to find my error.


Answer Source

Something like this?

function TrackDiscussion( $input ) {
    return preg_replace( "~\#(\w+)~i", '<a href="$1">#$1</a>', $input );

echo TrackDiscussion( 'Lorum #Ipsum  dolor sit amet, #consectetur adipiscing #elit.' );

Or only contain hashtag links?

function TrackDiscussion2( $input ) {
    preg_match_all( "~\#(\w+)~i", $input, $matches );
    $return = array();
    foreach( $matches[1] as $match ) {
        $return[] .= '<a href="'.$match.'">#'.$match.'</a>';
    return implode( ', ', $return );

echo TrackDiscussion2( 'Lorum #Ipsum  dolor sit amet, #consectetur adipiscing #elit.' );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download