CancelImage Upload

How to add slashes to a string in order to use speech or quotation marks in PHP

As you are no doubt aware speech or quotation marks in the wrong place can cause havoc within a PHP code. The following example for instance will without a doubt produce an error:

<?php

echo "And then Don said "PHP is giving me trouble with quotation marks"";

?>

Now it doesn't take a rocket scientist to find out what is wrong with the above example. As soon as the second quotation mark comes into play PHP thinks it is back to receiving a variable, and is therefore surprised when it is all of a sudden confronted with a group of words that have little meaning in PHP, and for sure are not variables.

So, how to prevent this? Well by adding a backslash of course. And to help matters here the functions addslashes() and addcslashes() will do all the work for us automatically. Of the two addcslashes is the more effective, as it will add a slash to a number of special symbols which need a slash adding to.

<?php

$stringWithSlashes = addcslashes($string);

?>

Note that these two functions should be used with post variables, or any other variable that is passed along. The following for instance will still produce a PHP error, since the definition inside the code is still wrong:

<?php

echo addcslashes("And then Don said "PHP is giving me trouble with quotation marks"");

?>

Whereas if you receive the sentence via HTML form, the addcslashes() will make the string workable:

<?php

echo addcslashes($_POST['string']);

?>

For the original example the slashes would have to be added manually:

<?php

echo "And then Don said \"PHP is giving me trouble with quotation marks\"";

?>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com