This is a naïve implementation of string escaping for JavaScript. As you’re actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:
$txt = json_encode($txt);
echo ““;
json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.
Reference :
https://stackoverflow.com/questions/4270665/how-to-handle-newlines-in-javascript-from-php