从php构建javascript时转义引号

Basically, I'm taking user input and passing it to a javascript function in a page from php. But because the user use's apostrophes, I'm getting errors. What's the proper escape function in php to use on a variable that will be surrounded by quotes. IE:

Some php:

$userString = "Joe's Pizza";
// escape here
echo "<script type=\"text/javascript\">myFunction('$userString');</script>";

Thanks much!

addslashes; e.g.

$userString = addslashes("Joe's Pizza");
print '<script type="text/javascript">myFunction('$userString');</script>";;

Wrap it in an object/associative array and use json_encode.

$array = array('data' => $userString);
$encoded_array = json_encode($array);
echo "<script type=\"text/javascript\">myFunction($encoded_array);</script>";

myFunction could look like:

function myFunction(obj)
{
  var data = obj.data;
  ... 
}

This also allows you to easily make the object more complex if needed.