Jaylen Jaylen - 7 months ago 25
PHP Question

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

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?

Answer

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>'))){}
Comments