6

Does anybody know how to prevent FILTER_SANITIZE_SPECIAL_CHARS from converting the line breaks ( \n ) into ( &#10 ; ).

I'm developing a simple commenting system for my website and I found that the php filter converts \n to so when using nl2br() there are no line breaks.

help please.

thanks :)

1
  • Do you have some code which shows the newlines being converted into semi-colons?
    – salathe
    Jun 30, 2010 at 15:44

1 Answer 1

14

filter_var with the FILTER_SANITIZE_SPECIAL_CHARS option is doing what it is supposed to do:

HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.

The newline character (\n) has an ASCII value of less than 32, so will be converted to &#10;. You could therefore use html_entity_decode to convert them back 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&#10;line 2
line 1
line 2

But I guess that defeats the object of using FILTER_SANITIZE_SPECIAL_CHARS in the first place.

If it is only the newline that is causing the problem, you could replace the HTML character entity (&#10;) with a newline character, before using nl2br():

echo str_replace('&#10;', "\n", $filtered);

Outputs:

line 1
line 2

Or perhaps even better, skip the middle step, and replace the HTML character entity (&#10;) with <br />:

echo str_replace('&#10;', '<br />', $filtered);

Outputs:

line 1<br />line 2

...but I'm not 100% sure what it is you are trying to do.

1
  • thank you so much! that works! I really tried that before sending asking but it was the wrong way ;) thanks a lot.
    – med87
    Jun 30, 2010 at 19:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.