Kadir Damene
Kadir Damene

Reputation: 358

converting BR tags into new lines in a textarea

This is a function I made which is supposed to convert every Br line break into a \n:

function br2nl($st){
    return preg_replace('/<br(\s+)?\/?>/i', "\n", $st);
}

However, the output is like this:

foo

bar

nuts

I want it to output something like:

foo <br>
bar <br>
nuts

Upvotes: 1

Views: 1136

Answers (1)

Andriy Kuba
Andriy Kuba

Reputation: 8263

Probably your HTML is

foo<br>
bar<br>
nuts<br>

So you already have "\n" and replacing br to "\n" you ends up with double "\n" like

foo \n\n bar \n\n nuts

it's looks like

foo

bar

nuts

For receiving output you suggest - you need to remove "\n" from the input HTML and then replace br to "\n"

The code would be

function br2nl($st){
  $st_no_lb = preg_replace( "/\r|\n/", "", $st );
  return preg_replace('/<br(\s+)?\/?>/i', "\n", $st_no_lb);
}

Upvotes: 1

Related Questions