I'm trying to insert a PHP EOT string into a js code and I need to encode it since it has some \n
in it. I can't do it with a simple jsonencode
because it returns the code with "
's and I don't need them there.
So i tried those two approaches which both return an error:
<?php
$string = $v['survey'];
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
<?php echo escapeJavaScriptText(); ?>
I've also tried:
<?php
$string = $v['survey'];
function javascript_escape($string) {
$new_str = '';
$str_len = strlen($string);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($string, $i, 1)));
}
return $new_str;
}
?>
<?php echo javascript_escape(); ?>
Both return:
Missing argument 1 for escapeJavaScriptText()
and Undefined variable: string in
But <?php echo $string; ?>
returns the code I need (just without the encoding).
What am I missing?