如何删除html特殊字符?

Pra*_*ant 54 php html-encode

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

  & © 
Run Code Online (Sandbox Code Playgroud)

等等

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

sch*_*der 108

使用以下方法解码它们html_entity_decode或删除它们preg_replace:

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

(从这里)

编辑:根据Jacco的评论替代

用{2,8}或其他东西替换'+'可能会很好.这将限制在未编码的'&'出现时替换整个句子的机会.

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

  • 这些字符实体在RSS/Atom/XML中无效.所以你可以做两件事:删除它们,或用等号替换它们. (4认同)
  • 将'+'替换为'{2,8]之类的东西可能会很好.这将限制在未编码的'&'出现时替换整个句子的机会. (3认同)

and*_*ndi 20

使用html_entity_decode转换HTML实体.

您需要设置charset才能使其正常工作.

  • 这个!您只需要在字符串上运行`html_entity_decode`,然后使用`strip_tags`,最后使用`filter_var($string, FILTER_SANITIZE_STRING)`。 (2认同)

小智 16

除了上面的好答案,PHP还有一个非常有用的内置过滤器功能:filter-var.

要删除HMTL字符,请使用:

$cleanString = filter_var($dirtyString, FILTER_SANITIZE_STRING);

更多信息:

  1. function.filter-VAR
  2. FILTER_SANITIZE_STRING


0xF*_*xFF 8

您可能需要在这里查看htmlentities()和html_entity_decode()

$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
Run Code Online (Sandbox Code Playgroud)