Escape double quotes of HTML attributes output by PHP

Phil picture Phil · Jul 8, 2009 · Viewed 29.5k times · Source

Often when writing PHP I'll have it output some HTML like this -

echo "<a href="../" title="link title">".$link_text."</a>";

Obviously this won't parse as I need to escape the double quotes in the attributes of the <a> element. Is there a regex that would quickly do this rather than me manually adding the backslashes?

One other thing - the regex shouldn't escape double quotes outside of the tag (e.g. where I've appended the $link_text variable.

Any ideas?

Answer

Greg picture Greg · Jul 8, 2009

You should just use single-quotes instead:

echo '<a href="../" title="link title">' . $link_text . '</a>';