php怎么输出js格式化字符串?
这里所谓js格式化字符串 是指从php程序输出的字符串可以直接被用作js字符串常量,而不会使js在运行过程中产生语法错误。
在很多时候我们需要调用php页面,从php页面动态生成js语句。而往往在些过程中,会遇到需要转换字符串的操作。以下这个函数可以解决这个问题:
function jsoutputformat ($str){$str = trim ($str);$str = str_replace ('\\s\\s', '\\s', $str);$str = str_replace (chr(10), '', $str);$str = str_replace (chr(13), '', $str);$str = str_replace ('', '', $str);$str = str_replace ('\\', '\\\\', $str);$str = str_replace ('"', '\\"', $str);$str = str_replace ('\\\'', '\\\\\'', $str);$str = str_replace ("'", "\'", $str);return $str;}
用法示例:
$output = '<table width="100%"><tr class="head"><td width="50%">中国</td><td>中华人民共和国</td></tr></table>';$output = jsoutputformat($output);echo "document.write(\"$output\");";
这样格式化后输出的结果如下:
document.write("<table width=\"100%\"><tr class=\"head\"><td width=\"50%\">中国</td><td>中华人民共和国</td></tr></table>");
js可能顺利运行。
更多相关知识,请访问!