Click to See Complete Forum and Search --> : Problem filtering out HTML


AlexFZ
08-10-2007, 11:26 AM
Hello.

For those who don't want to read all this: SHORT VERSION:
The code below can strip out all HTML tags except for <br /> tags fine, but I cannot figure out how to then put all of the characters back together and reform the string as a single variable.

LONG VERSION:
I am writing a simple guestbook script to try and gradually teach myself PHP and MySQL (or at least the basics).

I have run into a problem when I try to filter out all HTML in a submitted form field, except for the <br /> tag. I need to leave the <br /> tag as is, because I use the nl2br() function to change all of the line breaks into HTML <br /> tags. However, I do not want people to be able to enter their own HTML code into the field. The other fields aren't a problem, because I can just straight out filter all HTML in them without worrying.

I have already made a script that takes a string and strips all HTML from it except for a <br /> tag, but my problem is how to get that newly stripped string to become the original variable that will be entered into the databse.

If you are confused at all by what I mean, please have a look at the code. This script is pointed to in the in the form's ACTION attribute. It handles the entries and puts them into the database. I am only pasting the part that handles the HTML stripping in the "$gentry" field, which is the textarea for the comment in the guestbook.
// Use HTML breaks in the comment field
$gentry=nl2br($gentry);

// Strip all HTML except for breaks in the comment
$j = strlen($gentry);
for ($i=0; $i<$j; $i++) {
$char = substr($gentry, $i, 1);
if ($char=="<") {
$char2 = substr($gentry, $i+1, 1);
$char3 = substr($gentry, $i+2, 1);
$char4 = substr($gentry, $i+3, 1);
$char5 = substr($gentry, $i+4, 1);
$char6 = substr($gentry, $i+5, 1);
if ($char2!="b" && $char3!="r" && $char4!=" " && $char5!="/" && $char6!=">") {
$char=filter_var($char, FILTER_SANITIZE_SPECIAL_CHARS);
$char2=filter_var($char2, FILTER_SANITIZE_SPECIAL_CHARS);
$char3=filter_var($char3, FILTER_SANITIZE_SPECIAL_CHARS);
$char4=filter_var($char4, FILTER_SANITIZE_SPECIAL_CHARS);
$char5=filter_var($char5, FILTER_SANITIZE_SPECIAL_CHARS);
$char6=filter_var($char6, FILTER_SANITIZE_SPECIAL_CHARS);
} // Filter chars if
} // First character if
} // For loop

Any help would be greatly appreciated! Thanks :)

ellisgl
08-10-2007, 11:30 AM
$detagged = strip_tags($string, '<br/><br /><br>');
Strips all tags but br's.

AlexFZ
08-10-2007, 11:33 AM
Wow, I did all that stuff for no reason. I feel like an idiot haha.

The more you know!

Thanks again for helping, you've always helped me within 5 minutes of my posts too :P

ellisgl
08-10-2007, 11:36 AM
Hey - look at some of my questions I've posted or answers where I've used overly complex ways of getting something done. Then someone else corrects me and I'm like "D'oh!"