Given the following string:
asd <div> def foo </div> ghi <div> moo </div>
I want to remove all of the
's that are within <div>
s, resulting in:
asd <div> def foo </div> ghi <div> moo </div>
I can use any standard PHP stuff, but I'm not sure how to approach the problem. I couldn't figure out how to keep the contents inside the <div>
s while removing the
The reason why I need this is because WordPress's content filter adds
under strange situations. I can't simply remove all
because they might've been specifically entered by the user, but I need to remove all of them within the element that's having display problems caused by them
$text = "asd <div> def </div> ghi <div> moo </div>";
echo preg_replace_callback(
"#<div(.*?)>(.*? .*?)</div>#i",
"filter_nbsp",
$text);
function filter_nbsp($matches)
{
return "<div".$matches[1].">" . str_replace(" ","",$matches[2]) . "</div>";
}
That should work for entities between div elements closed as </div>
,
output
asd <div> def </div> ghi <div> moo </div>
The following works in your case:
$str = "asd <div> def </div> ghi <div> moo </div>";
$res = preg_replace("%<div>(.*?) (.*?)</div>%", "<div>$1$2</div>", $str);
But beware of some facts:
only one time, so multiple
s inside divs are untouched.So the abovementioned replacement is not a good solution at all. It's way better to first find the div tags with a (XML) parser function and then replace all
s.
simple_html_dom
$html = str_get_html('asd <div> def </div> ghi <div> moo </div>');
foreach($html->find('div') as $element) {
$a = $element->plaintext;
$element->innertext = preg_replace('{\ }','',$a);
}
echo $html;