Jump to content

Find hashtags ignore html


DHood

Recommended Posts

I'm attempting to take a string and find/replace all the hashtags into links. This works except it messes up the html in the string, I want to ignore all html entirely.

 

 

#testing <span style="color: #bbbbbb">#asdfasd</span> #test

 

Right now using this:

 

 

$string = preg_replace_callback('/#([a-zA-Z_]+)/', array($this, 'renderHashTag'), $string);

 

#testing, #bbbbbb, #asdfasd, and #test all get picked up and I don't want #bbbbbb or #asdfasd to. I've tried several different things before posting here, I just can't seem to figure out how to ignore the html tags, someone recommended removing them but I don't want to do that as some of it may be important to the styling.

Link to comment
Share on other sites

The biggest setback is the fact that you don't want to include #asdfasd. That one isn't actually inside an html tag the same way as #bbbbbb. By this logic..what would you say to the following?
 

<p>#testing <span style="color: #bbbbbb">#asdfasd</span> #test</p>

or
 

<div>#testing <span style="color: #bbbbbb">#asdfasd</span> #test</div>

or
 

<body>#testing <span style="color: #bbbbbb">#asdfasd</span> #test</body>

Point is virtually everything is "in" an html tag somehow. I can make a difference between #bbbbbb and the other 3, because #bbbbbb is part of a value in an html element attribute. But strictly speaking, there is no difference between #asdfasd and the #test or #testing. So first off, you need to be more specific about what you actually want to ignore. Anything inside an html tag or span tag specifically?

In any case, regex isn't really the best tool for parsing html. You should instead use a DOM parser to traverse the html elements.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.