简体   繁体   English

转义HTML输出的引号?

[英]Escaping quotes for HTML output?

So magic_quotes doesn't exist anymore in php, but I need a function like that (or maybe I don't?) 所以magic_quotes在php中已经不存在了,但是我需要一个这样的函数(或者也许我不这样做?)
Let me quickly explain what I want to do: 让我快速解释一下我想做什么:

<table>
    <button onclick="location.href='/test?colA=<?php echo $var1; ?>&colB=<?php echo $var1; ?>'">click</button>
</table>

The Problem: $var1 and $var2 can contain singlequotes and doublequotes. 问题:$ var1和$ var2可以包含单引号和双引号。

Here is what I tried, which did not work: 这是我尝试过的方法,但是没有用:

$var1 = str_replace('"','&quot;',$var1);
$var1 = str_replace('\'','&#39;',$var1);

$var2 = str_replace('"','&quot;',$var2);
$var2 = str_replace('\'','&#39;',$var2);

Applying urlencode on both vars would actually be sufficient. urlencode应用于两个变量实际上就足够了。 This escapes all special characters, including quotes. 这会转义所有特殊字符,包括引号。

Technically it's also in HTTP attribute context, so adding htmlspecialchars() would be professional. 从技术上讲,它也在HTTP属性上下文中,因此添加htmlspecialchars()将是专业的。

Most correctly, though this is slightly overpedantic, you would first cover the URL parameter context, then the JavaScript string context, then HTML. 最正确的是,尽管这有点过头了,但您首先要介绍URL参数上下文,然后是JavaScript字符串上下文,然后是HTML。

<table>
    <button onclick="location.href=<?= 
        htmlspecialchars(
            json_encode(
                "/test?" .
                http_build_query(
                    array("colA" => $var1, "colB" => $var2)
                )
            )
        )
    ?>">click</button>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM