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