在php中的文本中删除一个额外的换行符

时间:2015-11-19 14:36:41

标签: php regex preg-replace

我的问题与this one i added last night完全相反。 需要删除最后一个br标签。

输入:

Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.

输出

 Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.

我的尝试:

preg_replace("[((?:<br>)+)]","",$posttext)

删除所有休息。

2 个答案:

答案 0 :(得分:2)

您可以替换

<br><br>(?!<br)

<br>

preg_replace('/<br><br>(?!<br)/', "<br>", $posttext);

lookahead将阻止再匹配<br>

See demo at regex101

答案 1 :(得分:0)

大饱眼福这哈哈哈

如果Preg替换不起作用......

// cuts off one <br> as high as whatever $i is at

$string = "Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.";
$i = 10;

while($i > 0)
{
  $ii = 1;
  $brake = "<br>";
  $replace = "";
  while($ii < $i)
  {
   $brake .= "<br>";
   $replace .= "<br>";
   $ii++;
  }
$string = str_replace($brake,$replace,$string);
$i--; 
} 

 echo $string; // Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.

PS:如果没有preg替换它,它可以使用,虽然非常无效。