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

PHPz
Release: 2020-06-24 14:02:36
Original
2047 people have browsed it

​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;
}
Copy after login

用法示例:

$output = '
<table width="100%">
<tr class="head">
<td width="50%">中国</td>
<td>中华人民共和国</td>
</tr>
</table>
&#39;;
$output = jsoutputformat($output);
echo "document.write(\"$output\");";
Copy after login

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

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

JS可能顺利运行。

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!