addslashes() String Function

Sep 02, 2010 Author: City Hall

addslashes() is usually used to prepare a string for storage in a database or some kind of delimited format such as comma-separated values (CSV). The function places a single backslash in front of any backslashes (\), quotes (" or '') or null (\0) bytes in the string argument. This prevents the contents of the string from accidentally "breaking" the quoting of whatever format the string is being stored in. See the first example for a practical demonstration of how this can happen.
Example: Show how addslashes() transforms a string

<?php
echo "Before addslashes():\n";
echo $quote = <<<QUOTE
 "We all felt the majesty of the body...
  As we saw the artificial heart beat...
  the feeling was not aren't we great,
  but aren't we small."
              --- Dr William C DeVries\0\n\n
QUOTE;

echo "After addslashes():\n";
echo $cleaned_quote = addslashes($quote);
?>

Output:
Before addslashes():
 "We all felt the majesty of the body...
  As we saw the artificial heart beat...
  the feeling was not aren't we great,
  but aren't we small."
              --- Dr William C DeVries

After addslashes():
 \"We all felt the majesty of the body...
  As we saw the artificial heart beat...
  the feeling was not aren\'t we great,
  but aren\'t we small.\"
              --- Dr William C DeVries\0


views 4554
  1. Add New Comment