Jaylen Jaylen - 1 year ago 74
PHP Question

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

I am trying to remove all leading and trailing

in a string using PHP.

Here is an example

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

I want to return

<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 Source

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>'))){}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download