Web Programming, Linux System Administation, and Entrepreneurship in Athens Georgia

Perl function equivalent of PHP’s AddSlashes()

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;
}

5 Comments

  1. pim

    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

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

  3. Not Real

    How is this different than DBI’s quote method:

    https://search.cpan.org/~timb/DBI/DBI.pm#quote

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

  4. John May

    $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.
    **https://www.perlmonks.com/?node_id=678757

  5. James M.

    Thanks! This little routine saved me some time 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2025 Brandon Checketts

Theme by Anders NorenUp ↑