Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim all leading/trailing <br> code using php

Tags:

html

php

trim

I am trying to remove all leading and trailing <br> in a string using PHP.

Here is an example

<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>

I want to return

Hello<br>
World<br>
<p>This is a message<br>...</p>

I tried to do the following

echo trim($str, '<br>');

But it does not remove them. How can I remove the new line html code?

like image 355
Jaylen Avatar asked Jul 28 '26 19:07

Jaylen


1 Answers

Use preg_replace with the beginning ^ and end $ anchors:

$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);

Or for multiple lines:

$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);

You could also trim() it multiple times:

while($string !== ($string = trim($string, '<br>'))){}
like image 125
AbraCadaver Avatar answered Jul 30 '26 09:07

AbraCadaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!