filter_var with the filter_var option does what it should do:
HTML escape '"<> & and characters with an ASCII value less than 32, optionally strip or encode other special characters.
The newline character ( \n ) has an ASCII value less than 32, so it will be converted to . Therefore, you can use html_entity_decode to return them to their original characters:
$string = "line 1\nline 2"; $filtered = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS); echo "$filtered\n"; echo(html_entity_decode($filtered));
Outputs:
line 1 line 2 line 1 line 2
But I guess the FILTER_SANITIZE_SPECIAL_CHARS usage object wins FILTER_SANITIZE_SPECIAL_CHARS .
If this is only a newline problem, you can replace the HTML character character ( ) with a newline character before using nl2br() :
echo str_replace(' ', "\n", $filtered);
Outputs:
line 1 line 2
Or maybe even better, skip the middle step and replace the HTML character object ( ) with <br /> :
echo str_replace(' ', '<br />', $filtered);
Outputs:
line 1<br />line 2
... but I'm not 100% sure what you are trying to do.
source share