2

我的问题与这个问题类似,但我没有使用代码点火器。我将从数据库获得的变量回显到文本输入的 value 属性中。变量可能包含 ' 或 " 或任何其他特殊字符。

我试过:

<input type="text" name="myTextInput" value="<?= htmlspecialchars($dbValue, ENT_QUOTES); ?>" />

但它将引号输出为&quot;&#039;不是我想要的。我希望文本输入实际上包含用户键入的引号。

我应该使用 php 函数还是 javascript 函数来转义字符串?如果我不转义它,我会收到一个 javascript 错误,因为 $dbValue 字符串中的引号正在与值属性引号交互。

4

4 回答 4

5

然而,这正是你想要的。例如

如果您插入的数据是

Davy "Dead Pirate" Jones

然后你将它插入到一个输入字段中,你最终会得到

<input type="text" name="..." value="Davy "Dead Pirate" Jones" />

这将被解释如下:

<input> field with attributes:
    text -> 'text'
    name -> '...'
    value -> ' '   (a single space)
    Dead -> 
    Pirate ->
    " ?   danging quote
    Jones ->
    " ? -> another dangling quote

相比之下,在做了一个 html_entities 之后,你会有

 Davy &quot;Dead Pirate&quot; Jones

<input>并且可以毫无问题地插入该字段。

如果输入字段的值包含&quot;对用户可见的文字,那么您将进行一些双重编码。

于 2012-07-12T19:05:16.767 回答
4

你会想要使用html_entity_decode. 这是文档的示例:

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now
?>

参考http ://www.php.net/manual/en/function.html-entity-decode.php

于 2012-07-12T19:01:07.913 回答
2

您正在寻找 htmlspecialchars 的反面,请尝试使用 html_entity_decode。

这是您使用的代码html_entity_decode

<input type="text" name="myTextInput" value="<?= html_entity_decode($dbValue, ENT_QUOTES); ?>" />

这是手册的链接-> http://www.php.net/manual/en/function.html-entity-decode.php

如果您在使用它时遇到任何问题,您可能想查看这个问题,它有一个常见的编码问题-> https://stackoverflow.com/a/4638621/1065786

于 2012-07-12T19:02:22.893 回答
0

要将单引号、双引号和 html 标签显示为文本字段值,请尝试使用:

<?php
$formVal = htmlspecialchars($dbValue, ENT_COMPAT, 'utf-8');
// or this:
// $formVal = htmlspecialchars($dbValue);
?>

<!-- html -->
<form>
<input type="text" name="myTextInput" value="<?php echo $formVal; ?>" />
</form>

http://www.sitepoint.com/form-validation-with-php
https://www.inanimatt.com/php-output-escaping.html

于 2014-06-27T15:31:57.613 回答