在PHP中转义粘性表单的值中的双引号

Vir*_*dia 4 php forms validation filtering

我在制作一个粘性表单时会遇到一些麻烦,如果值有双引号,它会记住在表单提交时输入的内容.问题是HTML应该是这样的:

<input type="text" name="something" value="Whatever value you entered" />
Run Code Online (Sandbox Code Playgroud)

但是,如果短语:"我该怎么做?" 使用引号键入,生成的HTML类似于:

<input type="text" this?="" do="" i="" how="" value="" name="something"/>
Run Code Online (Sandbox Code Playgroud)

我怎么必须过滤双引号?我已经尝试过使用魔术引号,我使用了striplashes和addslashes,但到目前为止我还没有找到合适的解决方案.解决PHP问题的最佳方法是什么?

Gre*_*reg 13

你想要htmlentities().

<input type="text" value="<?php echo htmlentities($myValue); ?>">

  • htmlspecialchars应该足够了 (7认同)

the*_*art 11

以上将编码具有html实体代码的各种字符.我更喜欢使用:

htmlspecialchars($myValue, ENT_QUOTES, 'utf-8');
Run Code Online (Sandbox Code Playgroud)

这只会编码:

'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'
Run Code Online (Sandbox Code Playgroud)

您还可以在$ myValue上执行strip_tags以删除html和php标记.