rwkiii rwkiii - 8 months ago 51
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="'','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?


To escape nested quotes in PHP, use the \

 $confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="\'\',\'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="'','sharer','toolbar=0,status=0,width=548,height=325');" class="">Share on Facebook</a>