从字符串的末尾删除<br>

iam*_*ter 14 php regex preg-replace

正如标题所说,我有一个这样的字符串:

$string = "Hello World<br>hello world<br><br>";
Run Code Online (Sandbox Code Playgroud)

现在我想摆脱<br>这个字符串末尾的s所以它看起来像这样:

$string = "Hello World<br>hello world";
Run Code Online (Sandbox Code Playgroud)

我试过这个:

preg_replace('/^(<br>)*/', "", $string);
Run Code Online (Sandbox Code Playgroud)

但这没用.也许有人知道正确的正则表达式.

问候彼得

Ale*_*sky 18

你很接近,你在正则表达式的开头使用了^,这意味着"匹配字符串的开头".你最后想要$,这意味着"匹配字符串的结尾".

preg_replace('/(<br>)+$/', '', $string);
Run Code Online (Sandbox Code Playgroud)


Sco*_*ack 10

对于其他任何人来说,就像我一样,寻找一种从字符串末尾删除任何所有break标记的方法,包括:

<br> <br/> <br /> <br              /> <br      >
Run Code Online (Sandbox Code Playgroud)

我用了:

$string = preg_replace('#(( ){0,}<br( {0,})(/{0,1})>){1,}$#i', '', $string);
Run Code Online (Sandbox Code Playgroud)

效果很好.如果它们之间有空白区域,这也会剥离它们.你需要调整任何\n\r等,如果这是你需要的.

  • 它也可以更容易:`(?:\s*&lt;br *\/?&gt;\s*)+$` 结尾或 `^(?:\s*&lt;br *\/?&gt;\s *)+` 从一开始就烤制所有带有或不带有斜线的 br 标签,以及在斜线之前或标签之前/之后的任何空白 (2认同)

Ric*_*oth 6

我认为,从字符串末尾删除所有空格和 BR 的最佳解决方案是:

preg_replace('#(\s*<br\s*/?>)*\s*$#i', '', $string);
Run Code Online (Sandbox Code Playgroud)

在这里测试:

$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));
}
Run Code Online (Sandbox Code Playgroud)

这打印:

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)
Run Code Online (Sandbox Code Playgroud)