user3179854
user3179854

Reputation:

PHP strip_tags except certain characters

I am using strip_tags in PHP to remove HTML tags when echoing data.

My string looks like:

<br>
<br>
<br>
<br>
<br>
Test 1, Test2<br>
Test 3,<br>
<br>
<br>
<br>
<br>
<br>
Test 4<br>
Test 5<br>
<br>
Test 6 test 7

How can I remove the <br> tags that leave big gaps but keep the <br> tags between line gaps (like that between Test 1, Test2<br>Test3)?

And just remove the:

<br>
<br>
<br>
<br>
<br>

So the string will end up looking like:

Test 1, Test2<br>
Test 3,<br>
Test 4<br>
Test 5<br>
<br>
Test 6 test 7

Upvotes: 0

Views: 358

Answers (1)

Amal
Amal

Reputation: 76666

It's probably cleaner to do this in two steps:

// remove <br> tags
$text = preg_replace('#^(<br[\\s]*(>|\/>)\s*){2,}$#im', '', $text);

// remove empty lines - from http://stackoverflow.com/a/709684/
$text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", PHP_EOL, $text);

Explanation - #^(<br\s*(>|\/>)\s*){2,}$#im

  • ^ - beginning of the line anchor
  • ( - first capturing group
    • <br - literal characters <, followed by b, followed by r
    • \s* - any whitespace character, zero or more times
    • (>|\/>) - alternation - match both <br> and <br/>
    • \s* - followed by optional whitespace
  • ) - end of first capturing group
  • {2,} - match the previous group, 2 or more times
  • i - match both cases
  • m - make the pattern match lines separately

Output:

Test 1, Test2<br>
Test 3,<br>Test 4<br>
Test 5<br>
<br>
Test 6 test 7

Demo

Upvotes: 1

Related Questions