FlyingCat
FlyingCat

Reputation: 14288

How to filter html characters?

I have a question regarding the filter

I have the following:

$htmlData contains user input html string and it is like

$htmlData = array('<em>test</em>', 'text here','\n')

//I use htmlspecialchars function and want to filter \n out and save it to DB.

       $texts = htmlspecialchars($htmlData[$i]);

        if(!empty($texts) && $text != '\n'){
             echo $text;   //I still see '\n' here for some reason.
         }

I don't want to save '\n' to DB because it will just be blank in DB. Are there anyway to prevent this? Thanks for the help!

Upvotes: 0

Views: 296

Answers (2)

user1646111
user1646111

Reputation:

Use trim():

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab

For other solutions refer to this question: Remove new lines from string

Upvotes: 1

str
str

Reputation: 45039

$text != '\n' will just check whether the string contains a backslash followed by the letter "n". What you want to compare it with is a newline, so you have to use $text != "\n" instead.

Also see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Upvotes: 1

Related Questions