Search code examples
phpregexpreg-replacepreg-match

Making hash tags into links without ruining links that use the hash symbol


I have a post system that I'd like to have support both links and hash tags. The problem is that some links contain a #, themselves, and the code tries to convert the # in the link to more links!

A user might post "http://somelink.com#hashKeyword #hashtag"

Here is the code I'm working with. I believe it works, except for when links contain hashtags.

$theText = "http://somelink.com#hashKeyword #hashtag";

//Convert links
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($reg_exUrl, $theText, $url)) {
   $theText = preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a>', $theText);
}

//Convert hash tags
$theText = preg_replace("/#(\w+)/", '<a href="linktohashtag/#$1">#$1</span>', $theText);

Any help is greatly appreciated!


Solution

  • By using HamZa's comment and an answer on this question, I was able to fix the issue.

    I simply formatted the hashtag regex to only find tags that are after a space or the beginning of the post. That way, they don't conflict with the normal links.

    /(^|\s)#([A-Za-z_][A-Za-z0-9_]*)/

    Here's the new last line of code:

    $theText = preg_replace("/(^|\s)#([A-Za-z_][A-Za-z0-9_]*)/", '$1<a href="linktohashtag/#$2">#$2</span>', $theText);

    It works great! Thank you all for the discussion!