使用contenteditable div的结构替换数据库中的值

使用contenteditable div的结构替换数据库中的值

问题描述:

I'm printing a value of a mysql field on a contenteditable div and I need it to adopt the structure corresponding to it. With the same divs and line breaks br.

I have tried the nl2br function of php but it only generates line breaks br, so it does not work well for me. I need the complete structure.

For example:

<div id="textbox" contenteditable="true"><?php echo nl2br($text); ?></div>

Where $text is a text with line breaks from database.

So when executing nl2br, change them all by br.

I currently get this:

<div id="textbox" contenteditable="true">
  Line 1
  <br>
  Line 2
  <br>
  <br>
  Line 3
</div>

And I need to get this:

<div id="textbox" contenteditable="true">
  Line 1
  <div>Line 2</div>
  <div>
    <br>
  </div>
  <div>Line 3</div>
</div>

Which is what is generated automatically when writing on a contenteditable div.

A quick attempt at what your after, output looks OK, but make sure it works for what your after.

The idea is to just split the text into lines - start off with the first line of text as is, then add each subsequent line in <div> tags - if the line is blank - then set it to <br />...

$text = 'Line 1
Line 2

Line 3';

$lines = explode("
",$text);
$output = array_shift($lines);
foreach ( $lines as $line ) {
    $output .= "<div>".($line?:"<br />")."</div>";
}

echo $output;

With the sample above this gives...

Line 1<div>Line 2</div><div><br /></div><div>Line 3</div>