【问题标题】:PHP - Remove decoded HTML entities from stringPHP - 从字符串中删除解码的 HTML 实体
【发布时间】:2019-01-08 07:08:49
【问题描述】:

我正在尝试清理字符串,结果如下:

lt i gt 芽孢杆菌中抗砷基因的表征 lt i gt sp UWC 从成熟的粉煤灰酸性矿山排水中分离 中和固体

我正在尝试删除 lt、i、gt,因为它们是精简的 HTML 实体,似乎没有被删除。处理这个或其他我可以考虑的解决方案的最佳方法是什么?

这是我目前的解决方案:

/**
 * @return string
 */
public function getFormattedTitle()
{
    $string = preg_replace('/[^A-Za-z0-9\-]/', ' ',  filter_var($this->getTitle(), FILTER_SANITIZE_STRING));
    return $string;
}

这是一个示例输入字符串:

Assessing <i>Clivia</i> taxonomy using the core DNA barcode regions, <i>matK</i> and <i>rbcLa</i>

谢谢!

【问题讨论】:

标签: php string replace html-entities


【解决方案1】:

代替filter_var,试试strip_tags:http://php.net/manual/en/function.strip-tags.php

<?php
  //your input string
  $input_string = 'Assessing <i>Clivia</i> taxonomy using the core DNA barcode regions, <i>matK</i> and <i>rbcLa</i>';

  //strip away all html tags but leave whats inside
  $output_string = strip_tags($input_string);

  echo $output_string;
  //echos: Assessing Clivia taxonomy using the core DNA barcode regions, matK and rbcLa 

?>

【讨论】:

  • 我试过了,但结果是:Antibiotic resistance profiles of &amp;lt;i&amp;gt;Escherichia coli&amp;lt;/i&amp;gt; isolated from different water sources in the Mmabatho locality 我现在需要删除 &lt、&gt、&i 等...
  • 在这种情况下,我认为@Thomas David Baker 是正确的,您在屏幕上看到了 html 标签,但您的基础数据充满了 html 实体。当您显示示例输入字符串时,您是从浏览器中复制的还是从文本文件中复制的?
【解决方案2】:

更好的方法是 strip_tags(); 在此处查看手册: http://php.net/manual/ru/function.strip-tags.php 一个例子:

   public function getFormattedTitle()
    {
        return strip_tags($this->getTitle(), '<i>');
    }

【讨论】:

    【解决方案3】:

    输出中的 ltgt 告诉我,您拥有的字符串实际上更像:

    “使用核心 DNA 条形码区域 <i>matK</i> 和 <i>rbcLa</i> 评估 <i>君子兰</i> 分类法”

    当被视为纯文本时。

    您在上面显示的字符串将在浏览器中显示,它会解释 '<'作为 ''。 (这些通常称为“HTML 实体”,并提供了一种编码字符的方法,否则该字符会被解释为 HTML。)

    一种选择是这样处理:

    $s = "Assessing &lt;i&gt;Clivia&lt;/i&gt; taxonomy …";
    $s = html_entity_decode($s); // $s is now "Assessing <i>Clivia</i> taxonomy …"
    $s = strip_tags($s); // $s is now "Assessing Clivia taxonomy"
    

    但请注意,strip_tags 是一个非常幼稚的函数。例如,它会将 '12' 变成 '12'!所以你需要确保你所有的输入文本都是双 HTML 编码的,因为这个例子是为了让它完美地工作。

    【讨论】:

      猜你喜欢
      • 2011-05-12
      • 2015-03-07
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多