FILTER_SANITIZE_SPECIAL_CHARS problem with line breaks

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

I am developing a simple comment system for my site, and I found that the php filter converts \ n to so when using nl2br () there are no line breaks.

help me please.

thanks:)

+4
source share
1 answer

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 &#10; . 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&#10;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 ( &#10; ) with a newline character before using nl2br() :

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

Outputs:

 line 1 line 2 

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

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

Outputs:

 line 1<br />line 2 

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

+12
source

Source: https://habr.com/ru/post/1314335/


All Articles