Zanz
Zanz

Reputation: 21

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!

Upvotes: 1

Views: 78

Answers (2)

Zanz
Zanz

Reputation: 21

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!

Upvotes: 1

diggersworld
diggersworld

Reputation: 13080

Sounds like you're trying to get two different results with one formula, i.e. X = 1, X = 2... however X cannot equal both 1 and 2 at the same time. You need to make a choice and implement something different.

Generally a # in a URL will try to find an element within the HTML dom that contains a matching id attribute. So http://www.example.com/index.php#who-are-we would open the index page and then shift the browser view to the element <h1 id="who-are-we">. That could be any HTML element, I've just used a h1 for this example.

With regards to creating links on your site you may wish to create a script which parses them, making them URL friendly. So if the post title is How to work with twitter #hashtags, your script would replace spaces with hyphens, and strip everything non-alphanumerics or a space. So you get a link like how-to-work-with-twitter-hashtags.

Upvotes: 0

Related Questions