Escape double quotes of HTML attributes output by

2019-04-11 01:54发布

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?

6条回答
霸刀☆藐视天下
2楼-- · 2019-04-11 02:11

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楼-- · 2019-04-11 02:13

use single quotes or use heredoc. I'd prefer the last.

查看更多
对你真心纯属浪费
4楼-- · 2019-04-11 02:14

You should just use single-quotes instead:

echo '<a href="../" title="link title">' . $link_text . '</a>';
查看更多
放荡不羁爱自由
5楼-- · 2019-04-11 02:14

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.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-04-11 02:26

Use (This syntax dont worry about quotes etc)

echo <<<EOT
<a href="../" title="link title">$link_text</a>
EOT;
查看更多
手持菜刀,她持情操
7楼-- · 2019-04-11 02:26

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>
查看更多
登录 后发表回答