1

Lets say I have the following string (from a much larger string with multiple similiar strings)

$str = '<div class='testdiv remove'>randomtext</div>
<div class='testdiv'>randomtext <a href="#">randomtext</a></div>';

The class 'remove' was added through a javascript function. How would I remove all elements of the class 'remove' and all links so that the string becomes this:

$str = '<div class='testdiv'>randomtext </div>';

I can't use jquery to remove these tags since I have to feed this into a php library function. How would I remove these?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
JimK
  • 11
  • 1

2 Answers2

0

Use a dom parser http://simplehtmldom.sourceforge.net/

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
-1

use regular expression :)

$pattern = "/(?:<div class='testdiv remove'>[\s\S]+?</div>|<a[^>]+>[^<]+</a>)/i"
$str = preg_replace($pattern, "", $str);
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • Please don't do that. First of all, this doesn't fit his requirements, and second of all, [it's just a bad idea in general](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – Nightfirecat Aug 08 '11 at 22:19
  • i don't think this is bad idea, if he wants to remove then this is the solution, otherwise he'll be stuck in accessing parents and child nodes. – Aamir Rind Aug 08 '11 at 22:26
  • It's entirely a bad idea. Regular expressions should not be used to parse (X)HTML, since it is not a regular language. Not to mention the fact that, again, this _will not fit his requirements_. He needs only elements which have the class `remove` to be removed. – Nightfirecat Aug 08 '11 at 22:31