Jump to content


Photo

Find hashtags ignore html


  • Please log in to reply
1 reply to this topic

#1 DHood

DHood

    Member

  • Members
  • PipPip
  • 15 posts

Posted 24 July 2013 - 06:55 AM

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.


- DHood


#2 .josh

.josh

    .josh

  • Staff Alumni
  • 14,828 posts

Posted 24 July 2013 - 09:37 AM

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.



Did I help you? Feeling generous? Donate to me! || Donate to phpfreaks!
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com