php question about stripslashes

bitt3n

Senior member
Dec 27, 2004
202
0
76
why does stripslashes("\r\n\' ") strip the slash before the ' but not before the r and the n?

the output in the browser is just ' (with a new line generated in the html code corresponding to the \r\n without slashes stripped) instead of being rn', which you would expect if all slashes were stripped.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Because \r and \n are special characters, just like \s (space) or \w (word) or \d (digits) in regular expression.

When you call addslashes(), PHP will only add slashes to certain characters that may cause troubles when processing the script, such as ' (single quote), " (double quote), \ (backslash).
The opposite is true, that stripslashes() only remove slashes from the same characters.
 

bitt3n

Senior member
Dec 27, 2004
202
0
76
interesting.. so why does

echo (stripslashes(" \r\n\' "));

strip slashes only from before the ' (as in first post), but

echo (stripslashes(' \r\n\' '));

strips all three slashes? ie, why do single quotation marks make PHP unable to recognize the special characters?

thanks for your help
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Because of the nature of double quote and single quote.
When you are using double quote, all the characters in the double quotes are parsed by php.
So, something like:

$variable = 'hello';
stripslashes ("\n $variable \r \' world");

will first parse the \n into a new line, $variable into 'hello', and \r into line feed. Essentially, PHP will turn the statement to:

stripslashes ("[newline] hello [linefeed] \' world");

Before doing the stripslashes

On the other hand, using single quotes does not parse the contents enclosed by them, and PHP will treat them as is.
Exception in this case would be \', which tells PHP that you want the single quote to be part of the entry instead of end marker of your text inside stripslashes

$variable = 'hello';
stripslashes ('\n $variable \r \' world');

Since there is no parsing take place inside single quote, the statement will be evaluated as:

stripslashes ('\n $variable \r \' world');

And with that, stripslashes will remove the \ because that's what it's told to do.