Does anybody know how to prevent FILTER_SANITIZE_SPECIAL_CHARS from converting the line breaks ( \n ) into ( 
 ; ).
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 :)
Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
We can sanitize a URL by using FILTER_SANITIZE_URL. This function removes all chars except letters, digits and $-_. +! *'(),{}|\\^~[]`<>#%";/?:@&=.
Definition and Usage The FILTER_SANITIZE_STRING filter removes tags and remove or encode special characters from a string. Possible options and flags: FILTER_FLAG_NO_ENCODE_QUOTES - Do not encode quotes. FILTER_FLAG_STRIP_LOW - Remove characters with ASCII value < 32.
The FILTER_SANITIZE_EMAIL filter removes all illegal characters from an email address.
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
. 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 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 (
) with a newline character, before using nl2br()
:
echo str_replace(' ', "\n", $filtered);
Outputs:
line 1
line 2
Or perhaps even better, skip the middle step, and replace the HTML character entity (
) with <br />
:
echo str_replace(' ', '<br />', $filtered);
Outputs:
line 1<br />line 2
...but I'm not 100% sure what it is you are trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With