【问题标题】:Handling apostrophes when generating HTML with PHP使用 PHP 生成 HTML 时处理撇号
【发布时间】:2011-08-11 17:58:06
【问题描述】:

我正在根据 XML 配置值生成单选按钮。有时他们在文本中有撇号。在 PHP 中处理这些数据时,我似乎失去了撇号后的一切。例如:

<input type='radio' name='remove[]' value='Government wants to limit employers' communications about unionization'>

但是在表单 POST 之后将其转储出来时,我得到了这个值:

array(1) {
[0]=>
string(35) "Government wants to limit employers"
}

关于如何保存完整字符串的任何建议?谢谢!

【问题讨论】:

    标签: php html


    【解决方案1】:

    使用htmlspecialchars():

    <input type="radio" ... value="<?php echo htmlspecialchars($array[0], ENT_QUOTES) ?>" ... />
    

    它的明确目的是允许将任意文本安全地插入到 html 中,而不会“破坏”html。请注意“ent_quotes”选项。默认情况下 htmlspecialchars 只会处理 &lt;&gt;",但由于您使用的是 ',因此您需要告诉 htmlspecialchars 也处理这些选项。

    【讨论】:

    • 感谢马克的输入。使用 htmlspecialcharsENT_QUOTES 参数可以保留我的收音机值。但是,我最终将这个值写回到 XML 配置中。我相信特殊字符正在使我的 XML 损坏,因为我收到此错误:Warning: SimpleXMLElement::asXML() [simplexmlelement.asxml]: xmlEncodeEntitiesReentrant : input not UTF-8output conversion failed due to conv error, bytes 0x92 0x20 0x76 0x69 通过此代码:$old = simplexml_load_file($file); $bar-&gt;title = $_SESSION['title']; $old-&gt;asXML($file); 有什么想法吗?
    • htmspecialchars() 有一个参数来指定字符集,请看这里的手册页php.net/htmlspecialchars
    【解决方案2】:

    你可以转义字符串中的引号:value='Government wants to limit employers&amp;#39; communications about unionization' 转义它会导致这个问题停止。

    PHP 确实为此提供了函数,以防您的信息在变量中。只需使用htmlspecialchars

    【讨论】:

    • 感谢凯尔的回复,但是,我的价值观是动态的。
    • 我刚刚编辑了我的答案。查看 htmlspecialchars 函数或 addlashes 函数。
    • 这不是 HTML 的正确转义。应该是employers&amp;#39; communications。或者只是为该属性使用双引号而不是单引号。
    【解决方案3】:

    最简单的方法就是像这样使用双引号:

    <input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
    

    这几乎就是他们的原因。

    【讨论】:

      【解决方案4】:

      我通常坚持使用这两个简单的选项,两者都同样有效:

      1. 您可以将一种类型的引号封装在另一种类型中

      $var = " here single quotes ' are encapsulated in double quotes";
      $var = 'here double quotes " are encapsulated in single quotes';

      1. 您可以使用 \
      2. 转义引号

      $var = "just quote some mathematician: \"quot erat demonstrandum\".";

      【讨论】:

        【解决方案5】:

        您可以使用双引号将文本括起来:

        <input type='radio' name='remove[]' value="Government wants to limit employers' communications about unionization">
        

        更好的方法是将撇号替换为&amp;#39;

        <input type='radio' name='remove[]' value='Government wants to limit employers&quot; communications about unionization'>
        

        如果文本也包含双引号,这是一个更强大的解决方案。您应该将所有's 替换为&amp;#39;s,将"s 替换为&amp;quot;s。

        这可以使用htmlspecialchars(string $str) 轻松完成。 http://php.net/manual/en/function.htmlspecialchars.php

        【讨论】:

          猜你喜欢
          • 2012-02-05
          • 1970-01-01
          • 2011-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-08
          • 1970-01-01
          相关资源
          最近更新 更多