Jump to content

Strip all spans of a certain class in $content


Helmet

Recommended Posts

Ah sorry.. the sample I posted was a sample of what I was trying to remove from a much larger string containing lots of html, so I'm just trying to remove the tags and content contained within, that have a certain class.

 

I was just looking at another regular expressions match for square brackets, since all the spans I'm talking about are: <span class="foo">[ random content I can't predict ] </span>

 

$content = preg_replace('/\\[[^\\]]*\\]/', '', $content);

 

But this is interfering with the html in a part of the page that does not have square brackets.

To get you started thinking and to help others find better ways ...

<?php
function myReplace($html, $bad_class)
{
$pos = strpos($html, $bad_class);
while ($pos !== FALSE)
{
	// find last instance of '<' in the string up until $bad_class
	$start = strrpos(substr($html, 0, $pos), '<');
	// find last instance of '>' in the string up until $bad_class
	$stop = strrpos(substr($html, 0, $pos), '>');
	// replace the text from '<' to '>' with nothing
	$html = substr_replace($html, '', $start, $stop);

	// find first instance of '<' in the string after $bad_class
	$start = strpos(substr($html, $pos), '<');
	// find first instance of '>' in the string after $bad_class
	$stop = strpos(substr($html, $pos), '>');
	// replace the text from '<' to '>' with nothing
	$html = substr_replace($html, '', $start, $stop);

	// keep looking for more $bad_class
	$pos = strpos($html, $bad_class);
}
return $html;
}

$html = 'Lots of <span class="foo">data</span> with multiple <span class="bar">classes</span> in it.';
$bad_class = 'class="bar"';
$html = myReplace($html);
?>

 

Now, this will only work if there are no '<' or '>' in the text that is between the tags you are trying to eliminate. It should remove the tag before, but not it's corresponding closing tag if there is a '<' or '>' wrapped inside the tag.

 

You could argue that you could make it better by searching for the tag type once you found the '<' or '>' and then trying to find it's corresponding closing tag based on what tag it is. But even then, what if you were trying to write code wrapped in the tag.

 

You could find a scenario to screw over almost anything.

Hope this helps.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.