" that you will need to remove to make this work. * * var myJs = < ?php * echo php_to_js("anything you like"); * ? >; // No quotes necessary * var embeddded = "Hello, < ?php * echo php_to_js("John Doe"); * ? >, how are you?"; * * @license MIT with additional non-advertising clause * @see https://rumkin.com/license/ * @param string $str The string to escape and wrap in quotes * @param boolean $skipQuotes If true, don't wrap string with quotes * @return string Escaped and probably quoted string for JavaScript */ function php_to_js($str, $skipQuotes = false) { $replacements = array( "/( "$1\"+\"$2", // Break up " '\\\\', // Escape backslashes '/"/' => '\\"', // Escape quotes "/'/" => "\\'", // Escape apostrophes "/\r\n/" => "\n", // Convert DOS newlines into Unix "/\r/" => "\n", // Convert Mac newlines into Unix "/\n/" => "\\n\"+\n\"", // Convert Unix newlines ); $str = preg_replace(array_keys($replacements), array_values($replacements), $str); if ($skipQuotes) { return $str; } return '"' . $str . '"'; }