Skip to content

Instantly share code, notes, and snippets.

@Chengings
Created March 17, 2014 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chengings/9599473 to your computer and use it in GitHub Desktop.
Save Chengings/9599473 to your computer and use it in GitHub Desktop.
Escape php string to javascript string
<?php
/**
* Escape php string to javascript string
* @param string $str
* @return string escaped string
*/
function escape_javascript_string($str){
// if php supports json_encode, use it (support utf-8)
if (function_exists('json_encode')) {
return json_encode($str);
}
// php 5.1 or lower not support json_encode, so use str_replace and addcslashes
// remove carriage return
$str = str_replace("\r", '', (string) $str);
// escape all characters with ASCII code between 0 and 31
$str = addcslashes($str, "\0..\37'\\");
// escape double quotes
$str = str_replace('"', '\"', $str);
// replace \n with double quotes
$str = str_replace("\n", '\n', $str);
return "'{$str}'";
}
$test_case = array(
'',
"https://demo/path/download.html?q=query",
"~!@#$%^&*(){}[]`/=?+\|-_;:'\,<.>",
'These are the problems => . \ \' \\ \\\\ \\\\\\ \\\\\\\\ "',
);
foreach ($test_case as $test_str) {
print '<script>';
print 'alert(' . escape_javascript_string($test_str) . ')';
print '</script>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment