Using Strings In PHP addslashes

Using the addslashes function in PHP

One of the problems with strings is quotes. This is because we use quotes to define a string. The other problem is if we store them in a database, the database might have problems with a string if in the middle of it we have a single or double quote.

A useful function to avoid this is the addslashes function. You would call this function using the following code:

addslashes($var);
That is very simple, but not very effective as we didn’t actually save it. So lets try it again.
1. $somestring = “This is my string. It contains a single quote ‘ which might break something.”;
2. $somestring = addslashes($somestring);
3. print $somestring;
That would result in printing the line:
This is my string. It contains a single quote \’ which might break something.

Did you notice the \ before the quote? That tells PHP that the item after the \ should be considered part of the value and not the end of the value. This is also good for if you needed to define a string with a double quote. You would just use \” to add a double quote into your string.

So where would I use this?

The most common use of this is when you have a user submitted form that has a text area. Adding slashes to the submitted text will help prevent anything from breaking.

Other functions for manipulating strings: