PHP-generated javascript and quote marks

2020-08-05 10:05发布

I'm generating some javascript in my PHP code, and I need to assign some php variables to javascript variables. Unfortunately, sometimes my PHP variables contain quote marks. for instance:

$foo = "'Dis here be a \"string\"";
print "<script type='text/javascript'>var foo = '{$foo}';</script>";

will generate a javascript error because the resulting javascript will look like this:

<script type='text/javascript'>var foo = '"'Dis here be a \"string\"';

I know I can use regexp on $foo to replace all ' marks with \' but this is hard for various reasons. Is there anything I can do short of that? Something akin to the perl q() function...

7条回答
Rolldiameter
2楼-- · 2020-08-05 10:59

Tried doing this?

$foo = "'Dis here be a \"string\"";
echo '<script type="text/javascript">var foo = "'.addslashes($foo).'";</script>';

See: http://php.net/manual/en/function.addslashes.php

查看更多
登录 后发表回答