There are already native functions to escape for HTML and JS strings: [`htmlspecialchars()`][1] and [`json_encode()`][2]. See [this related question on Stack Overflow][3] As for `innerHTML`, simply don't use it. Use `textContent` instead. If you wish to allow for formatting (for example, in comments or posts), I recommend [Markdown](http://daringfireball.net/projects/markdown/syntax) [1]: http://devdocs.io/php/function.htmlspecialchars [2]: http://devdocs.io/php/function.json-encode [3]: http://stackoverflow.com/q/23740548/871050