Reputation: 459
For example:
StackOverflow<br>
<br>
<br>
<br>
<br>
is
<br>
<br>
<br>
<br>
a
<br>
community.
To:
StackOverflow
<br>
<br>
is
<br>
<br>
a
<br>
community.
If there are more than 2 <br>
in a string, it should delete all the <br>
and keep only two.
Code so far:
$txt_unclean = trim(nl2br($_POST['txt_content']));
$txt_content = strip_tags($txt_unclean, '<br>');
What is the next step? How do I allow no more than 2 <br>
.
Upvotes: 0
Views: 605
Reputation: 7341
Since you have access to the string before newlines are converted into <br>
s, this is how I'd do it:
<?php
$string = <<<END
1
2
3
4
5
END;
$string = trim(nl2br(preg_replace('/(\r?\n){3,}/', '$1$1', $string)));
echo $string;
Output:
1<br />
2<br />
<br />
3<br />
<br />
4<br />
<br />
5
Upvotes: 4
Reputation: 173572
If your mark-up is controlled like that, you could use preg_replace
to match more than two consecutive <br>
:
$txt_content = preg_replace('/(<br>\s*){3,}/', '$1$1', $txt_content);
To also match self-closing tags:
$txt_content = preg_replace('/(<br\s*/>\s*){3,}/', '$1$1', $txt_content);
Otherwise, I would consider using a DOM parser to do this work; having said that, it's not as easy :)
Upvotes: 6