I was seeing today the addslashes and addcslashes in php.net, but did not get the point on what is the difference between them and what are the characters escaped in these two.
<?php
$originaltext = 'This text does NOT contain \\n a new-line!';
$encoded = addcslashes($originaltext, '\\');
$decoded = stripcslashes($encoded);
//$decoded now contains a copy of $originaltext with perfect integrity
echo $decoded; //Display the sentence with it's literal \n intact
?>
If i comment the $decoded variable and echo $encoded, i get the same value which is in the original string.
Can anyone clearly explain me the difference and use of these two.
addslashes
only escapes
single quote ('), double quote ("), backslash () and NUL
You can use addcslashes
to escape an arbitrary set of characters.
echo addcslashes("where's the party?", "party");
yeilds
whe\re's \the \p\a\r\t\y?
This can be useful when you need to create arbitrary control characters, or to prepare data for transport/use in arbitrary formats. For example, if you wanted to escape user input before using it as part of a regular expression, you could do the following
preg_match('/match something here plus' . addcslashes($userInput, ".\\+*?[^]($)") . '/', $foo);
However, this is equivalent to quotemeta
, but this is just one example.
More explanation
It is sometimes confusing for people new to the method, and in my opinion against the defacto set forth by the rest of the PHP library for the second parameter to be a string list, as this doesn't show up anywhere else in the library (to my knowledge).
It makes more sense for some people, and would be more conforming, if the second parameter were an array.
echo addcslashes("where's the party?", array("p", "a", "r", "t", "y"));
It may help some to visualize it this way, which can then be transformed into the following:
echo addcslashes(
"where's the party?",
implode("", array("p", "a", "r", "t", "y"))
);
addcslashes is used to escape characters you pass as the second parameter.
If you try reading the docs of stripcslashes, you'll find "Recognizes C-like \n, \r ..., octal and hexadecimal representation."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With