Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • addslashes

    Posted on March 25th, 2009 RubyLove No comments

    Addslashes takes a string as an argument, and returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote [ ' ], double quote [ " ], backslash [ \ ] and NULL (the NULL byte).

    PHP

    echo addslashes("Here's some money for your lunch");
    // => Here\'s some money for your lunch

    Ruby

    puts "Here's some money for your lunch".gsub(/['"\\\x0]/,'\\\\\0');
    # => Here\'s some money for your lunch

    As you can see above, the easiest way to emulate the PHP function addslashes() in Ruby is to use regular expressions.