views:

216

answers:

6

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

A: 

Are you sure? Isn't it:

var foo = ''Dis here be a "string"'


In order to prevent the double ' try:

$foo = "\'Dis here be a \"string\"";

or

$foo = '\\\'Dis here be a "string"';
powtac
+2  A: 

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

thephpdeveloper
Addslashes() is sufficient in this case, but won't escape *every* character that could potentially bork a js string.
Frank Farmer
addslashes is what i was looking for, and seems to work for now.
Igor
@Frank is right though, it won't take into account everything related to a javascript string.
Doug Neiner
+1  A: 

This should be a step in the right direction:

addcslashes($str, "\"\r\n\\\t/\0..\37");
Frank Farmer
+2  A: 

I use json_encode().

http://ie2.php.net/manual/en/function.json-encode.php

TRiG
A: 

Since you are using the final value in JavaScript, I would use json_encode:

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

And it will correctly output:

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

Notice I didn't put an extra set of quotes around the json_encode function. It will add the necessary quotes to make it a valid JavaScript string automatically.

Doug Neiner
A: 

It's also worth nothing that you can use a PHP file as a JavaScript file

<script type="text/javascript" src="js/main.php"></script>

And you're able to execute PHP code in that file, and write to the JavaScript file by echoing.

Zurahn