保留php mysql中的所有html空格

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.

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 or . This means that your code would output something like:

function test($param){
 return TRUE;
}

OR

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

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

Assuming that you're going to use pre tags:

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

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

try this, works excellently

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