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.
addslashesonly escapesYou can use
addcslashesto escape an arbitrary set of characters.yeilds
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
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.
It may help some to visualize it this way, which can then be transformed into the following: