I've never used PHP, but looking through its manual I found the addcslashes[1] function, which escapes the specified characters with backslashes in the style of C.
Thanks, the php api is humongous and I wasn't aware of that. I still think it would be nice to have a collection of "how to safely produce a lua string" snippets in multiple languages.