Perl function equivalent of PHP’s AddSlashes()

Posted on April 16th, 2007 in General by Brandon

Here is a perl equivalent of PHP’s AddSlashes() function. It’s a quick an dirty way to clean up text to insert into a database. There are better ways to do this. It should exactly mimic PHP’s function. It adds slashes before single quotes(‘), double-quotes(“), backslashes(\), and NULL bytes (\0).

sub AddSlashes {
    $text = shift;
    ## Make sure to do the backslash first!
    $text =~ s/\\/\\\\/g;
    $text =~ s/'/\\'/g;
    $text =~ s/"/\\"/g;
    $text =~ s/\\0/\\\\0/g;
    return $text;

4 Responses to 'Perl function equivalent of PHP’s AddSlashes()'

Subscribe to comments with RSS or TrackBack to 'Perl function equivalent of PHP’s AddSlashes()'.

  1. pim said,

    on May 2nd, 2007 at 4:02 am

    I’m not a Perl programmer but I needed to change the expressions to make it work in my PostgreSQL Perl stored Procedure.

    $text =~ s/\\/\\\\/g;
    $text =~ s/’/\\’/g;
    $text =~ s/”/\\”/g;
    $text =~ s//\/g;

  2. Mary Shaw said,

    on September 21st, 2007 at 3:05 pm

    You can do all of those regexes in one line- something like …
    $term =~ s/([\\\’\”])/\\$1/gi;

  3. Not Real said,

    on August 3rd, 2009 at 8:14 am

    How is this different than DBI’s quote method:

    Is this for when you are doing database work but not using DBI? (which is just crazy talk)

  4. John May said,

    on August 5th, 2009 at 4:29 pm

    $term =~ s/([\\\’\”])/\\$1/gi; Is not the same, the backslash needs to be escaped first. The one liner will escape the first character that appears in $term. Also /i isn’t needed and is very wasteful*. To prevent SQL injection it’s better to use placeholders** where possible.

    *Friedl, J., 2006. Mastering Regular Expressions 3rd ed., O’Reilly Media, Inc.

  5. James M. said,

    on September 1st, 2011 at 10:46 pm

    Thanks! This little routine saved me some time 🙂

Post a comment