Search code examples
phpjavascriptquotesquoting

PHP-generated javascript and quote marks


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...


Solution

  • 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