Well, preg_replace_all("/([^\])'/","$1\'",$yourStrHere)
will do what you're asking:
- "/([^\])'/" yields the regex /([^\])'/, which says "match on any single character that's not a backslash followed by a single quote, and capture the character before the quote."
- "$1\'" says "replace with the captured character followed by a backslash and a single quote"
BUT...
Bill's answer about parametrized queries using the mysqli or PDO APIs is really, really good advice. It's easier and more effective to let your database API handle this than to do it yourself -- the people who wrote these APIs (and the people who worked on the native backends for those APIs) have probably put more time and effort into addressing security and performance issues than most of us can hope to spend ourselves.