Escape double quotes of HTML attributes output by PHP

霸气de小男生 提交于 2019-12-19 04:09:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!