Home  >  Article  >  Backend Development  >  ​PHP怎么输出JS格式化字符串

​PHP怎么输出JS格式化字符串

PHPz
PHPzOriginal
2016-06-02 11:28:402045browse

​PHP怎么输出JS格式化字符串

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>
&#39;;
$output = jsoutputformat($output);
echo "document.write(\"$output\");";

这样格式化后输出的结果如下:

 document.write("<table width=\"100%\"><tr class=\"head\"><td width=\"50%\">中国</td><td>中华人民共和国</td></tr></table>");

JS可能顺利运行。

更多相关知识,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn