toooft
toooft

Reputation: 23

Prevent <br> after <div>

I'm wondering how to remove all <br/> existing right after a div tag. Is this possible? As soon as some regular text has been printed after the <div> tag, <br/> should be allowed again.

The <br/> is added because of nl2br.

I don't want the users to be able to break the formatting of my pages by hitting enter a lot. This would be great to be able to fix.

Thank you.

Upvotes: 0

Views: 469

Answers (4)

alekwisnia
alekwisnia

Reputation: 2354

$string = preg_replace('/<div>(<br[^>]*>\s*)+/', '<div>', '$string');

This is based on: How to convert multiple <br/> tag to a single <br/> tag in php

Upvotes: 1

PiTheNumber
PiTheNumber

Reputation: 23542

$count = 1;
while ($count != 0)
{
    $string = str_replace('</div><br/>' , '</div>' , $string, $count);
}

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131861

The better solution is to prevent nl2br() from putting the HTML-breaks at the beginning and end of the string.

$text = nl2br(trim($text));

Upvotes: 2

Dunhamzzz
Dunhamzzz

Reputation: 14798

A simple str_replace will sort it, just check which sort of <br> <br/> <br /> tag that nl2br() is using,

$string = str_replace('</div><br />' , '</div>' , $string);

Upvotes: 1

Related Questions