Created
March 17, 2014 13:48
-
-
Save Chengings/9599473 to your computer and use it in GitHub Desktop.
Escape php string to javascript string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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