【问题标题】:How to remove html special chars?如何删除html特殊字符?
【发布时间】:2010-10-14 01:06:27
【问题描述】:

我正在为我的应用程序创建一个 RSS 提要文件,我想在其中删除 HTML 标记,这是由 strip_tags 完成的。但是strip_tags 没有删除 HTML 特殊代码字符:

  & © 

等等

请告诉我任何可以用来从我的字符串中删除这些特殊代码字符的函数。

【问题讨论】:

    标签: php html-encode


    【解决方案1】:

    使用html_entity_decode 转换 HTML 实体。

    您需要设置字符集以使其正常工作。

    【讨论】:

    • 这更正确,因为当我们只是替换  使用空字符串我们得到不正确的结果 - 所有不可破坏的空间都被折叠
    • 这个!您只需要在字符串上运行html_entity_decode,然后使用strip_tags,最后使用filter_var($string, FILTER_SANITIZE_STRING)
    【解决方案2】:

    你可能想看看 htmlentities() 和 html_entity_decode() here

    $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
    

    【讨论】:

      【解决方案3】:

      要么使用html_entity_decode 解码它们,要么使用preg_replace 删除它们:

      $Content = preg_replace("/&#?[a-z0-9]+;/i","",$Content); 
      

      (来自here

      编辑:根据 Jacco 的评论替代

      将“+”替换为 {2,8} 什么的。这将限制 更换整个的机会 未编码的 '&' 时的句子 现在。

      $Content = preg_replace("/&#?[a-z0-9]{2,8};/i","",$Content); 
      

      【讨论】:

      • 用 '{2,8] 或其他东西替换 '+' 可能会很好。当存在未编码的“&”时,这将限制替换整个句子的机会。
      • 谢谢,添加了您的评论和答案的替代版本。
      • 但是为什么要删除这些字符呢?
      • 那些字符实体在 RSS/Atom/XML 中无效。所以你可以做两件事:删除它们,或者用它们的等价物替换它们。
      • 在剥离 HTML 以将其作为替代的纯文本正文在电子邮件中发送时,可能需要删除它们。
      【解决方案4】:

      无需使用 preg 正则表达式引擎的普通字符串方法:

      function remEntities($str) {
        if(substr_count($str, '&') && substr_count($str, ';')) {
          // Find amper
          $amp_pos = strpos($str, '&');
          //Find the ;
          $semi_pos = strpos($str, ';');
          // Only if the ; is after the &
          if($semi_pos > $amp_pos) {
            //is a HTML entity, try to remove
            $tmp = substr($str, 0, $amp_pos);
            $tmp = $tmp. substr($str, $semi_pos + 1, strlen($str));
            $str = $tmp;
            //Has another entity in it?
            if(substr_count($str, '&') && substr_count($str, ';'))
              $str = remEntities($tmp);
          }
        }
        return $str;
      }
      

      【讨论】:

        【解决方案5】:

        看起来你真正想要的是:

        function xmlEntities($string) {
            $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
        
            foreach ($translationTable as $char => $entity) {
                $from[] = $entity;
                $to[] = '&#'.ord($char).';';
            }
            return str_replace($from, $to, $string);
        }
        

        它将命名实体替换为它们的等价物。

        【讨论】:

          【解决方案6】:
          <?php
          function strip_only($str, $tags, $stripContent = false) {
              $content = '';
              if(!is_array($tags)) {
                  $tags = (strpos($str, '>') !== false
                           ? explode('>', str_replace('<', '', $tags))
                           : array($tags));
                  if(end($tags) == '') array_pop($tags);
              }
              foreach($tags as $tag) {
                  if ($stripContent)
                       $content = '(.+</'.$tag.'[^>]*>|)';
                   $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
              }
              return $str;
          }
          
          $str = '<font color="red">red</font> text';
          $tags = 'font';
          $a = strip_only($str, $tags); // red text
          $b = strip_only($str, $tags, true); // text
          ?> 
          

          【讨论】:

            【解决方案7】:

            我用来执行任务的函数,加入schnaader所做的升级是:

                mysql_real_escape_string(
                    preg_replace_callback("/&#?[a-z0-9]+;/i", function($m) { 
                        return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); 
                    }, strip_tags($row['cuerpo'])))
            

            此函数删除每个 html 标记和 html 符号,转换为 UTF-8 准备保存在 MySQL 中

            【讨论】:

            • 创建一个 rss 提要,而不是保存到 sql
            【解决方案8】:

            除了上面的好答案,PHP 还内置了一个非常有用的过滤函数:filter-var。

            要删除 HMTL 字符,请使用:

            $cleanString = filter_var($dirtyString, FILTER_SANITIZE_STRING);

            更多信息:

            1. function.filter-var
            2. filter_sanitize_string

            【讨论】:

            • 我知道线程有点旧,但我希望解决同样的问题......不幸的是 filter_var 需要 5.2 或更高版本......否则这将是答案(至少对于我的具体问题)。谢谢。
            【解决方案9】:

            这可能会很好地删除特殊字符。

            $modifiedString = preg_replace("/[^a-zA-Z0-9_.-\s]/", "", $content); 
            

            【讨论】:

              【解决方案10】:

              我所做的是使用:html_entity_decode,然后使用strip_tags 删除它们。

              【讨论】:

                【解决方案11】:

                试试这个

                <?php
                $str = "\x8F!!!";
                
                // Outputs an empty string
                echo htmlentities($str, ENT_QUOTES, "UTF-8");
                
                // Outputs "!!!"
                echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
                ?>
                

                【讨论】:

                • 记下“为什么你的代码有效”?所以其他人会很清楚。
                【解决方案12】:
                $string = "äáčé";
                
                $convert = Array(
                        'ä'=>'a',
                        'Ä'=>'A',
                        'á'=>'a',
                        'Á'=>'A',
                        'à'=>'a',
                        'À'=>'A',
                        'ã'=>'a',
                        'Ã'=>'A',
                        'â'=>'a',
                        'Â'=>'A',
                        'č'=>'c',
                        'Č'=>'C',
                        'ć'=>'c',
                        'Ć'=>'C',
                        'ď'=>'d',
                        'Ď'=>'D',
                        'ě'=>'e',
                        'Ě'=>'E',
                        'é'=>'e',
                        'É'=>'E',
                        'ë'=>'e',
                    );
                
                $string = strtr($string , $convert );
                
                echo $string; //aace
                

                【讨论】:

                • 这不能回答 OPs 问题
                【解决方案13】:

                你可以试试htmlspecialchars_decode($string)。它对我有用。

                http://www.w3schools.com/php/func_string_htmlspecialchars_decode.asp

                【讨论】:

                【解决方案14】:

                如果您想转换 HTML 特殊字符,而不仅仅是删除它们以及剥离内容并为纯文本做准备,那么这就是适合我的解决方案...

                function htmlToPlainText($str){
                    $str = str_replace('&nbsp;', ' ', $str);
                    $str = html_entity_decode($str, ENT_QUOTES | ENT_COMPAT , 'UTF-8');
                    $str = html_entity_decode($str, ENT_HTML5, 'UTF-8');
                    $str = html_entity_decode($str);
                    $str = htmlspecialchars_decode($str);
                    $str = strip_tags($str);
                
                    return $str;
                }
                
                $string = '<p>this is (&nbsp;) a test</p>
                <div>Yes this is! &amp; does it get "processed"? </div>'
                
                htmlToPlainText($string);
                // "this is ( ) a test. Yes this is! & does it get processed?"`
                

                html_entity_decode w/ENT_QUOTES | ENT_XML1 转换像&amp;#39; 这样的东西 htmlspecialchars_decode 转换像&amp;amp; 这样的东西 html_entity_decode 转换像'&amp;lt; 这样的东西 并且 strip_tags 会删除所有剩余的 HTML 标签。

                编辑 - 添加 str_replace(' ', ' ', $str);和其他几个 html_entity_decode() 继续测试表明需要它们。

                【讨论】:

                • 还添加 str_replace(" ", " ", $str);这样  不要像我的情况那样隐藏某种特殊的字符。
                【解决方案15】:

                如果您在 WordPress 中工作并且像我一样只需要检查一个空字段(并且在看起来像一个空白字符串的地方有大量随机 html 实体),那么请查看:

                sanitize_title_with_dashes( string $title, string $raw_title = '', string $context = 'display' )
                

                Link to wordpress function page

                对于不使用 WordPress 的人,我发现这个功能对于创建我自己的消毒剂非常有用,看看完整的代码,它真的很深入!

                【讨论】:

                  【解决方案16】:

                  如果“删除 HTML 特殊字符”的意思是“适当地替换”怎么办?

                  毕竟,看看你的例子......

                  &nbsp; &amp; &copy;
                  

                  如果您将其剥离为 RSS 提要,您不应该想要等效的吗?

                  " ", &, ©
                  

                  或者也许您不完全想要等价物。也许您希望 &amp;nbsp; 被忽略(以防止太多空间),然后让 &amp;copy; 实际上得到更换。让我们制定一个解决方案来解决这个问题的任何人的版本......

                  如何选择性替换 HTML 特殊字符

                  逻辑很简单:preg_match_all('/(&amp;#[0-9]+;)/' 抓取所有匹配项,然后我们简单地构建一个可匹配项和可替换项列表,例如str_replace([searchlist], [replacelist], $term)。在我们这样做之前,我们还需要将命名实体转换为对应的数字,即"&amp;nbsp;" 是不可接受的,但"&amp;#00A0;" 可以。 (感谢it-alien's solution to this part of the problem.

                  工作演示

                  在这个演示中,我将&amp;#123; 替换为"HTML Entity #123"。当然,您可以将其微调为您想要的任何类型的查找替换。

                  我为什么要做这个?我将它与 从 UTF8 字符编码的 HTML 生成富文本格式一起使用。

                  查看完整的工作演示:

                  Full Online Working Demo

                      function FixUTF8($args) {
                          $output = $args['input'];
                          
                          $output = convertNamedHTMLEntitiesToNumeric(['input'=>$output]);
                          
                          preg_match_all('/(&#[0-9]+;)/', $output, $matches, PREG_OFFSET_CAPTURE);
                          $full_matches = $matches[0];
                          
                          $found = [];
                          $search = [];
                          $replace = [];
                          
                          for($i = 0; $i < count($full_matches); $i++) {
                              $match = $full_matches[$i];
                              $word = $match[0];
                              if(!$found[$word]) {
                                  $found[$word] = TRUE;
                                  $search[] = $word;
                                  $replacement = str_replace(['&#', ';'], ['HTML Entity #', ''], $word);
                                  $replace[] = $replacement;
                              }
                          }
                  
                          $new_output = str_replace($search, $replace, $output);
                          
                          return $new_output;
                      }
                      
                      function convertNamedHTMLEntitiesToNumeric($args) {
                          $input = $args['input'];
                          return preg_replace_callback("/(&[a-zA-Z][a-zA-Z0-9]*;)/",function($m){
                              $c = html_entity_decode($m[0],ENT_HTML5,"UTF-8");
                              # return htmlentities($c,ENT_XML1,"UTF-8"); -- see update below
                              
                              $convmap = array(0x80, 0xffff, 0, 0xffff);
                              return mb_encode_numericentity($c, $convmap, 'UTF-8');
                          }, $input);
                      }
                  
                  print(FixUTF8(['input'=>"Oggi &egrave; un bel&nbsp;giorno"]));
                  

                  输入:

                  "Oggi &amp;egrave; un bel&amp;nbsp;giorno"

                  输出:

                  Oggi HTML Entity #232 un belHTML Entity #160giorno

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2022-08-03
                    • 1970-01-01
                    • 2011-10-10
                    • 1970-01-01
                    • 2014-05-14
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多