【问题标题】:How to remove HTML escape sequence characters from the string in PHP?如何从 PHP 中的字符串中删除 HTML 转义序列字符?
【发布时间】:2015-08-31 12:05:26
【问题描述】:

假设,我有一个包含此类字符串的以下字符串变量。

$sample_String = "Dummy User graded your comment \"\r\n\t\t\t\t\tdoc_ck.docx\r\n\t\t\t\t\tDownload\r\n\t\t\t\t\t\" that you posted.";

现在我不想让这些 HTML 字符出现在我的字符串中。

我应该如何以有效和可靠的方式删除它们?我想要最终的输出字符串如下:

$sample_String = "Dummy User graded your comment \"doc_ck.docx Download\" that you posted.";

当它显示在浏览器中时,出现在 " 之前的 '\' 将消失,浏览器中的字符串将如下所示:

虚拟用户对您发布的评论“doc_ck.docx 下载”进行了评分。

不是吗?

谢谢。

到目前为止,我已经尝试了以下代码但没有成功:

function br2nl($buff = '') {
    $buff = mb_convert_encoding($buff, 'HTML-ENTITIES', "UTF-8");
    $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
    $buff = trim($buff);

    return $buff;
  }
$sample_String = br2nl(stripslashes(strip_tags($sample_String)));

【问题讨论】:

  • 那些不是 HTML 实体,而是 C 转义。使用stripcslashes 可以恢复原始字符。或按正则表达式剥离它们(之前或之后)。
  • @mario : 请用我试过的代码检查我更新的问题。
  • 对不起。这使得更不清楚发生了什么。输入字符串现在来自哪里?它看起来如何? (var_dump 作为块文本)。或者$sample_String = "…"; 赋值在你的代码中是怎样的? (因为那时逃逸已经被扩大了)。 -- 请提供更多上下文。 (想象一下,你必须猜测目的是什么......)

标签: php html string html-entities html-escape-characters


【解决方案1】:

如果您只想删除\r(回车)\n(换行符)和\t(制表符),您可以这样做:

$string = "Dummy User graded your comment \"\r\n\t\t\t\t\tdoc_ck.docx\r\n\t\t\t\t\tDownload\r\n\t\t\t\t\t\" that you posted.";
$string = str_replace(array("\r", "\n", "\t"), "", $string);

如果您想保留换行符(并让它们显示在浏览器中),请执行以下操作:

$string = "Dummy User graded your comment \"\r\n\t\t\t\t\tdoc_ck.docx\r\n\t\t\t\t\tDownload\r\n\t\t\t\t\t\" that you posted.";
$string = nl2br(str_replace(array("\r", "\t"), "", $string));

HTMLentities 是像 &amp;quot;&amp;#063; 这样的序列

【讨论】:

  • 请用我试过的代码检查我更新的问题。
【解决方案2】:

像这样使用正则表达式:

<?php
$str = "Dummy User graded your comment \"\r\n\t\t\t\t\tdoc_ck.docx\r\n\t\t\t\t\tDownload\r\n\t\t\t\t\t\" that you posted.";
echo preg_replace('/[\r\n\t]+/m','',$str);

【讨论】:

    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    相关资源
    最近更新 更多