Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addslashes and addcslahes

Tags:

php

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.

like image 778
Kevin Avatar asked May 08 '10 23:05

Kevin


2 Answers

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"))
);
like image 140
Justin Johnson Avatar answered Sep 25 '22 02:09

Justin Johnson


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."

like image 20
Kemo Avatar answered Sep 26 '22 02:09

Kemo