Remove <br>'s from the end of a string

You're close, you used ^ at the start of the regexp, which means "match the start of the string." You want $ at the end, which means, "Match the end of the string."

preg_replace('/(<br>)+$/', '', $string);

Just for anyone else who comes along this, like I, looking for a way to remove any all break tags from the end of a string, including:

<br> <br/> <br /> <br              /> <br      >

I used:

$string = preg_replace('#(( ){0,}<br( {0,})(/{0,1})>){1,}$#i', '', $string);

to great effect. This will also strip them, if they have white-space between each. You'll need to adjust for any \n\r etc, if that's what you require.


I think, that the best solution for removing all spaces and BRs from the end of the string is this:

preg_replace('#(\s*<br\s*/?>)*\s*$#i', '', $string);

Test here:

$arr = [
  '<something>else that</needs>to <br>  <BR      />      <br/>  ',
  '<something>else that</needs>to <br>',
  '<something>else that</needs>to    <br/>  ',
  '<something>else that</needs>to     ',
  '<something>else that</needs>to<br/>',
  ];

foreach ($arr as $string) {
 var_dump(preg_replace('#(\s*<br\s*/?>)*\s*$#i', '', $string));
}

This prints:

test.php:11:string '<something>else that</needs>to' (length=30)
test.php:11:string '<something>else that</needs>to' (length=30)
test.php:11:string '<something>else that</needs>to' (length=30)
test.php:11:string '<something>else that</needs>to' (length=30)
test.php:11:string '<something>else that</needs>to' (length=30)