title: Escaping Javascript in PHP
body: <p>I'm looking for the best way to escape some Javascript text in PHP, and <code>json_encode</code> is the wrong tool for the job.</p>
  
  <p>The problem comes from this line:
  <code><pre>
  echo " onclick=\"SwitchDiv('" . $option . "')\"";
  </pre></code>
  If there's an apostrophe in <code>$option</code>, this is a juicy ball of client-side fail.  But doing a straight <code>json_encode</code> (which works perfectly well in other contexts) doesn't help:
  <code><pre>
  echo " onclick=\"SwitchDiv(" . json_encode($option) . ")\"";
  </pre></code>
  That creates an output string of <code>onclick="SwitchDiv("athlete's foot")"</code>, resulting in premature termination of the <code>onclick</code> value.  (Which also happens if I enclose the <code>onclick</code> value in single quotes.)</p>
  
  <p>Is there an elegant way around this?  Should I just funnel the <code>json_encode</code> output through a regex that will escape the single quotes?</p>