如何过滤HTML字符?

时间:2013-07-29 23:55:11

标签: php html

我对filter

有疑问

我有以下内容:

$htmlData包含用户输入html字符串,就像

$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.
         }

我不想将'\n'保存到数据库,因为它在DB中只是空白。反正有没有阻止这个?谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

使用trim()

  

此函数返回一个字符串,其中删除了空格   str的开头和结尾如果没有第二个参数,trim()将会   剥去这些字符:

" " (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

对于其他解决方案,请参阅此问题:Remove new lines from string

答案 1 :(得分:1)

$text != '\n'将检查字符串是否包含反斜杠后跟字母“n”。您要与之比较的是换行符,因此您必须改为使用$text != "\n"

另见http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double