newCodex
newCodex

Reputation: 72

Remove one extra line break in a text in php

My question is exactly opposite to this one i added last night . Need to remove the last br tag.

Input:

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

Output

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

My try:

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

It removes all breaks.

Upvotes: 1

Views: 72

Answers (2)

Ian Thompson
Ian Thompson

Reputation: 187

Feast your eyes on this hahaha

If Preg replace doesn't work...

// 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: If theres no preg replace for this, it is usable albeit very inefficent.

Upvotes: 0

bobble bubble
bobble bubble

Reputation: 18490

You can substitute

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

to <br>

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

The lookahead will prevent to match any more <br>

See demo at regex101

Upvotes: 2

Related Questions