我正在我的 PHP 代码中生成一些 javascript,并且我需要将一些 php 变量分配给 javascript 变量。不幸的是,有时我的 PHP 变量包含引号。例如:
$foo = "'Dis here be a \"string\"";
print "<script type='text/javascript'>var foo = '{$foo}';</script>";
将生成一个 javascript 错误,因为生成的 javascript 如下所示:
<script type='text/javascript'>var foo = '"'Dis here be a \"string\"';
我知道我可以在 $foo 上使用正则表达式将所有 '
标记替换为 \'
但由于各种原因这很困难。除此之外我还能做些什么吗?类似于 perl q()
函数...
最佳答案
尝试过这样做吗?
$foo = "'Dis here be a \"string\"";
echo '<script type="text/javascript">var foo = "'.addslashes($foo).'";</script>';
关于PHP 生成的 javascript 和引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1760325/