Renato Probst
Renato Probst

Reputation: 6054

Keep all html whitespaces in php mysql

i want to know how to keep all whitespaces of a text area in php (for send to database), and then echo then back later. I want to do it like stackoverflow does, for codes, which is the best approach?

For now i using this:

$text = str_replace(' ', '&nbs p;', $text);

It keeps the ' ' whitespaces but i won't have tested it with mysql_real_escape and other "inject prevent" methods together.

For better understanding, i want to echo later from db something like:

 function jack(){
    var x = "blablabla";
 }

Thanks for your time.

Upvotes: 0

Views: 3574

Answers (2)

Clinton Agburum
Clinton Agburum

Reputation: 29

try this, works excellently

$string = nl2br(str_replace(" ", "  ", $string));
echo "$string";

Upvotes: 1

Steven
Steven

Reputation: 6148

Code Blocks

If you're trying to just recreate code blocks like:

function test($param){
    return TRUE;
}

Then you should be using <pre></pre> tags in your html:

<pre>
    function test($param){
        return TRUE;
    }
</pre>

As plain html will only show one space even if multiple spaces/newlines/tabs are present. Inside of pre tags spaces will be shown as is.

At the moment your html will look something like this:

function test($param){
&nbsp;&nbsp;&nbsp;&nbsp;return TRUE;
}

Which I would suggest isn't desirable...

Escaping

When you use mysql_real_escape you will convert newlines to plain text \n or \r\n. This means that your code would output something like:

function test($param){\n return TRUE;\n}

OR

<pre>function test($param){\n    return TRUE;\n}</pre>

To get around this you have to replace the \n or \r\n strings to newline characters.

Assuming that you're going to use pre tags:

echo preg_replace('#(\\\r\\\n|\\\n)#', "\n", $escapedString);

If you want to switch to html line breaks instead you'd have to switch "\n" to <br />. If this were the case you'd also want to switch out space characters with &nbsp; - I suggest using the pre tags.

Upvotes: 1

Related Questions