Saturday, February 21, 2009

Add and strip slashes

Good programmers know that they can't trust user-inputted data. We do as much as we can to validate and try to prevent bad data from getting into our applications. But there is even some perfectly valid data that can cause trouble, especially when you're dealing with databases. The single apostrophe is a common occurrence and gotcha for the newbies when they discover the tail end of their string didn't make it into the database.


Our PHP programmer friends have a few different functions at their disposal. Native to PHP are the addslashes() and stripslashes() functions, which basically do what they say. In more common usage these days is the MySQL-native function, mysql_real_escape_string(), which can handle a wider variety of situations. I'm going to go a little bit further and handle the backspace and horizontal tab characters.


The regular expression we'll be using to add slashes is ([\000\010\011\012\015\032\042\047\134\140]), and to remove slashes we'll use \\([\000\010\011\012\015\032\042\047\134\140]). The only difference is the extra pair of slashes at the beginning. These handle, respectively: null, backspace, horizontal tab, new line, carriage return, substitute, double quote, single quote, backslash, and grave accent.


No comments: