1

I'm currently using this code to print a multiple lines of text from database

$query_content= "select * from home ";
$result_content= mysql_query($query_content,$con);
while ($text = mysql_fetch_array($result_content))
{
    $content = $text['homecontent']; 
}

And using this HTML code:

<p> 
<?php print $content; ?>
<p/>

The text inside the database is:

abc
def
ghi

But I'm getting this

abc def ghi

Any ideas?

Thanks.

2 Answers 2

5

You can use the built in function nl2br in php for this. Which converts \n\r (new line) to html's <br>.

<p> 
    <?php
        print nl2br( $content );
    ?>
<p/>

If, and hopefully, you have a xhtml or html5 compatible website you should put the second parameter to true to make the <br> xhtml compatible, <br />

<p> 
    <?php
        print nl2br( $content, true );
    ?>
<p/>
Sign up to request clarification or add additional context in comments.

Comments

3
echo str_replace(array("\r\n", "\n", "\r"), "<br>", $content);

Problem consists in, that in text you have a line breaks "\n", "\r" or his combinations, which in html displayed as spaces (space character). To insert real "line break" in html, tag <br/> must be used. So i wrote simple example of replacing all line breaks symbols to <br> html-tag.

In php exists special function string nl2br ( string $string [, bool $is_xhtml = true ] ) which do almost the same, but, i think, more quickly and correctly.

1 Comment

In my example, the author of question will understand the principle of html, i suppose... And second... i just forgot about this function :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.