Escaping strings with control characters, quotes and backslashes for subsequent use in MySQL commands.
MySQL has documented a number of backslash escape sequences that need to be used to pass certain values in SQL commands: https://dev.mysql.com/doc/refman/5.7/en/string-literals.html
It's crucial to escape existing backslashes first to prevent double-escaping, before escaping the various control sequences:
<?php
$result = str_replace(
array( '\\', "\0", "'", "\x8" /* BS */, "\n", "\r", "\t", "\x1A" /* Ctrl+Z */ ),
array( '\\\\', '\\0', '\\\'', '\\b', '\\n', '\\r', '\\t', '\\Z' ),
$value );
?>
This code is NOT intended to protect against SQL insertions, it's intended to PRESERVE string content correctly, if it contains control characters.