开发者

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

开发者 https://www.devze.com 2023-02-03 02:19 出处:网络
As the title says I have a string like this: $string = 开发者_如何学Python"Hello World<br>hello world<br><br>";

As the title says I have a string like this:

$string = 开发者_如何学Python"Hello World<br>hello world<br><br>";

I would like to get rid of the <br>s at the end of the string so it looks as follows:

$string = "Hello World<br>hello world";

I tried this:

preg_replace('/^(<br>)*/', "", $string);

but it didn't work. Maybe someone knows the right regex.


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)


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

EDIT: Oops, this should work now.


Regular expressions are powerful, but I think this case is more simple, rtrim should work

$string = rtrim($string,'<br>');


You could try the strip_tags function:

http://php.net/manual/en/function.strip-tags.php

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号