in reply to Using regex to add a single backslash to escape quotes, instead of 2 backslashes or 0

Just for fun, here is a fix to your function.

use strict; use warnings; my $message = q(O'REILLY); my $sql_message = sql_escape( $message); print "$sql_message"; sub sql_escape { my $text = shift; $text =~ s/'/\\'/g; $text =~ s/"/\\"/g; return $text; }

Use the module!

  • Comment on Re: Using regex to add a single backslash to escape quotes, instead of 2 backslashes or 0
  • Download Code

Replies are listed 'Best First'.
Re^2: Using regex to add a single backslash to escape quotes, instead of 2 backslashes or 0
by wink (Scribe) on Jul 26, 2012 at 21:17 UTC

    For completeness, here's WHY this fixes your function so you can maybe avoid similar issues in the future.

    $text = "O'REILLY"; $text =~ s/'/\\'/g; # $text is now O\'REILLY $text =~ s/"/\\"/g; # Unchanged $text =~ s/\\/\\\\/g; #$text is not O\\'REILLY

    So you properly replace it with a single backslash, but then you tell it to replace all single backslashes with double backslashes. If you wanted to do this properly, move the 3rd line above the 1st. But everyone is right, use the module.

      Wow, thanks for that. Such a basic mistake. :)