问题
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?
回答1:
You should just use single-quotes instead:
echo '<a href="../" title="link title">' . $link_text . '</a>';
回答2:
Solutions I can come up with (not without escaping):
Single quotes
echo '<a href="../">' . $link_text. '</a>';
Use double quotes
echo "<a href='../'>$link_text</a>";
Sprintf
echo sprintf('<a href="../">%s</a>', $link_text);
Use HEREDOC
echo <<<EOF <a href="../">$link_text</a> EOF;
Use template engine like smarty
Exit PHP-mode:
?><a href="../"><?php echo $link_text ?></a><?php // other code...
BTW, be sure to use htmlspecialchars()
on $link_text
variable, or you’ll have a XSS security hole.
回答3:
Use (This syntax dont worry about quotes etc)
echo <<<EOT
<a href="../" title="link title">$link_text</a>
EOT;
回答4:
I'd strongly suggest using templating instead of trying to build strings.
In raw PHP:
<a href="../" title="link title"><?php echo $link_text; ?></a>
回答5:
use single quotes or use heredoc. I'd prefer the last.
回答6:
I think you can use
http://www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email='.$email.'&hash='.$hash.'
"<a href="//www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email="$email&hash=$hash>Click Here to Active</a>"
try it.
来源:https://stackoverflow.com/questions/1097135/escape-double-quotes-of-html-attributes-output-by-php