时间:2011-01-06 18:02:26

标签: php regex preg-replace

6 个答案:

答案 0 :(得分:18)

答案 1 :(得分:10)

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

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

我用过:

$string = preg_replace('#(( ){0,}<br( {0,})(/{0,1})>){1,}$#i', '', $string);
效果很好。如果它们之间有空白区域,这也会剥离它们。你需要调整任何\ n \ r等,如果这是你需要的。

答案 2 :(得分:3)

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

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

在这里测试:

$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) {
  echo var_dump(preg_replace('#(\s*<br\s*/?>)*\s*$#i', '', $string));
}

打印:

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)

答案 3 :(得分:1)

答案 4 :(得分:0)

正则表达式很强大,但我认为这种情况更简单, rtrim 应该有效

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

答案 5 :(得分:-1)

您可以尝试使用strip_tags函数:

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