-1

The preg_replcae in this code is from another answer on this site, and is supposed to replace all spans and their contents with nothing i.e remove all spans and their content. But, why doesn't it work?

$string = <<<STR
<span>Span 1</span>
<div>DIV 1</div><div class="text">DIV 2</div>
<span> Span 2 </span>
<div class="apache">DIV 3</div>
<span>
Span 3
</span>
<span>
    Span 4
        </span>

STR;

$string = preg_replace("/<span[^>]+\>/is","",$string);

echo $string;

The end result I was hoping to get is:

<div>DIV 1</div><div class="text">DIV 2</div>
<div class="apache">DIV 3</div>
// no spans and their content
// everything else remains
Norman
  • 6,159
  • 23
  • 88
  • 141

1 Answers1

0

[^>]+ matches one or more characters, so <span> wont match. Use * there instead. Then, because you're trying to match everything in between, let's match all the content (.*?), and then the </span> closing tag. /<span[^>]*>.*?<\/span>/is becomes our final regex.

<?php

$string = <<<STR
<span>Span 1</span>
<div>DIV 1</div><div class="text">DIV 2</div>
<span> Span 2 </span>
<div class="apache">DIV 3</div>
<span>
Span 3
</span>
<span>
    Span 4
        </span>

STR;

$string = preg_replace("/<span[^>]*>.*?<\/span>/is","",$string);

echo $string;

You can see the output here: https://3v4l.org/X9C53

Blue
  • 22,608
  • 7
  • 62
  • 92