0

I'm testing a preg_replace function, and I return from an ajax function the processed data (after I process the data through preg_replace, I put it through htmlentities() ):

My test string is:

pr     eg123 ~!@#$%^&*()-+={}|[]:;<            >?    "...,'/... 

I'm trying to make sure all those characters aren't replaced. My replace function is:

$string = preg_replace('/[^a-zA-Z0-9\s+\n\r,.\/~!@#\$%\^&*()\+={}\[\]|:;<>?\'"-]/', '', $string);

I return both the data from "echo" and after going through htmlentities() to see the difference. when I return the data using alert(data), I get:

pr     eg123 ~!@#$%^&*()-+={}|[]:;<            >?    "...,'/... 



pr     eg123 ~!@#$%^&amp;*()-+={}|[]:;&lt;            &gt;?    &quot;...,&#039;/...

respectively. However, when I put either of those into $("#div").html(data), I get:

pr eg123 ~!@#$%^&*()-+={}|[]:;< >? "...,'/...

so the multiple spaces are lost. Why does the .html() function reduce the spaces? And how can I fix this? Thanks

Harvard
  • 29
  • 1
  • 7
  • Because that's how HTML works... To actually show those spaces, use ` `. – Derek 朕會功夫 Apr 22 '14 at 02:14
  • This link might help http://stackoverflow.com/questions/433493/why-do-multiple-spaces-in-an-html-file-show-up-as-single-spaces-in-the-browser – steven Apr 22 '14 at 02:14
  • the link helps a little. It offers the idea of using the "pre" tags, but not sure how I can apply that here. This would be user submitted text. – Harvard Apr 22 '14 at 02:25
  • Using `
    ` tags or the css `white-space` seems to be the only way to preserve spaces. As an aside comment, your preg_replace can be shorten: `preg_replace('/[^]!-[\^a-~\s]+/', '', $string);`
    – Casimir et Hippolyte Apr 22 '14 at 02:34

1 Answers1

0

remove "\s+" from your regular expression and try again

"I'm trying to make sure all those characters aren't replaced." you mean it?

so i make a test like below:

    $string = "~!@#$%^&*()-+={}|[]:;<            >?";
// $string = preg_replace('/[^a-zA-Z0-9]/', '', $string);

echo "'", $string, "'";

output is

'~!@#$%^&*()-+={}|[]:;< >?'

if you want keep whole white space between "<" and ">" in $string, i can say that no way, if you wanna output the same white spaces as you input: there are two way can make this:

1> use <pre> tage
2> use &nbsp; replace the white space

does you want these? if you want to keep all? why use regular?

TechStone
  • 141
  • 6