1

So i have a PHP class value that has the following text inside

$classvalue =
  'line1 line1

  line2 line2

  line3 line3';

How can i convert this into proper HTML markup?

$classvalue =
  'line1 line1
  <br>
  line2 line2
  <br>
  line3 line3';
Key
  • 396
  • 4
  • 15

4 Answers4

5

Use nl2br to replace new line characters with br tag

$classvalue = nl2br($classvalue);
littleibex
  • 1,705
  • 2
  • 14
  • 35
2

Either use nl2br:

$classvalue = nl2br($classvalue);

Or, loop the new lines and replace blank lines with <br> (Covered in another StackOverflow thread).

Something like this (untested):

$output_lines = "";
foreach(preg_split("/((\r?\n)|(\r\n?))/", $classvalue) as $line){
    if (strlen($line) > 0) {
        $output_lines .= $line;
    } else {
        $output_lines .= "<br />";
    }
} 
Community
  • 1
  • 1
Daniel Morris
  • 6,852
  • 8
  • 25
  • 30
2

You could go further and do

preg_replace("/[\r\n]/","<p>",$classvalue);
Mateusz Majewski
  • 280
  • 1
  • 10
2

You can use the below codes:

Either:

$return = preg_replace("/[\r\n]/","<p>",$classvalue);
// Regex contidion

Or:

$return = nl2br($classvalue);
// for new line separator