Best way to remove illegal characters from a string

Do not do this in the client!

In PHP simply use PDO and parameters for your queries.  This will completely deal with SQL injection problems and charsets issues.