lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Florian Berger wrote:

> What is the best way to make strings safe when using
> database and files (saving string to them)? I'm trying to
> do something like in PHP:
> http://www.php.net/manual/en/function.addslashes.php

-- Escape any single quote with another (ANSI SQL-style):
function escapesinglequotes(s)
  return (string.gsub(s, "%'", "''"))
end -- addslashesansi

-- Backslash-escape special characters:
function addslashes(s)
  -- Double quote, single quote, and backslash (per the PHP
  -- manual):
  s = string.gsub(s, "(['\"\\])", "\\%1")
  -- The null character gets turned into a pair of printing
  -- characters by PHP addslashes.  Let's do the same:
  return (string.gsub(s, "%z", "\\0"))
end -- addslashes

Note that both of these functions leave it to you to add the
final set of quotes around the result.

If you want to escape a string suitably for Lua itself, do
this:

s = string.format("%q", s) -- This does add the outside set
  -- of quotes.

-- 
Aaron

"PHP combines the orthogonality of sh with the elegance
of <font color=ad0000> Fatal error: Cannot redeclare
quuxitate() (previously declared in -:4) in - on line 6
</font>