rwkiii rwkiii - 4 months ago 19
PHP Question

Escape single quotes in string containing single and double quotes

I have a PHP string that contains single and double quotes, but am having a rough time getting it escaped properly. Even tried online quotify sites, but their result errors also.

$confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="window.open('http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F','sharer','toolbar=0,status=0,width=548,height=325');" class="">Share on Facebook</a>';


I don't think the double quotes need to be escaped. Still, all of my attempts result in HTTP 500 when loading the page.

How do the single quotes inside this string get escaped?

Answer

To escape nested quotes in PHP, use the \

 $confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="window.open(\'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F\',\'sharer\',\'toolbar=0,status=0,width=548,height=325\');" class="">Share on Facebook</a>';

For a complicated case with lots of quotes, it may be more readable and practical to use a heredoc:

$confirmation .= <<<EOT
  <a title="Share on Facebook" target="_blank" href="javascript:void(0)" onclick="window.open('http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F','sharer','toolbar=0,status=0,width=548,height=325');" class="">Share on Facebook</a>
EOT;
Comments