[Solved] Issue with trim function

Hi,

I needed to remove all break line tags from the beginning and end of below string, but trim() function removes more than expected and I couldn’t work out the reason for this.

$b = "  <br /><br /><strong>abc</strong> <br />";
$trimmed = trim($b, "<br />");

Outputs:

strong>abc</strong

Instead of:

<strong>abc</strong>

Hi Sam32,

The reason this is happening is because trim removes characters from the beginning and end of a string, so your second argument is treated as a list of characters (<, b, r, , /, >) to remove… which includes the opening and closing chevron from the opening and closing strong tags respectively.

You could instead use the str_replace function to remove the br tags:

$b = "  <br /><br /><strong>abc</strong> <br />";
$trimmed = trim(str_replace('<br />', '', $b));

Note that this method removes all br tags, not just those at the beginning or end of the string.

Hi fretburner,

Thanks for your reply.

I would like to remove just those at the beginning and end of the string considering also that there might be some whitespaces in between br tags for example.

Edit: Solved meanwhile.

$b=preg_replace('{^(?:<br />|</br>|\s+)+}', '', $b);
$b=preg_replace('{(?:<br />|</br>|\s+)+$}', '', $b);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.