欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php drupal7 d7 drupal 7 把 html 反转义 AG chatgpt 有大用 有大大用

在 Drupal 7 中,如果 HTML 实体(如 &lt;br /&gt;)被转义输出,而不是渲染为实际的 <br /> 标签,是因为内容被过滤或转义了。以下是几种 反转义 HTML 的方法:


1. 使用 check_markup() 强制解析 HTML

php
<?php print check_markup($field_value, 'full_html'); ?>
  • 适用场景:直接从数据库读取的字段(如 $node->body[und][0]['value']

  • 作用:确保 HTML 标签(如 <br />)被正确解析

  • 参数

    • $field_value:存储的原始内容(可能含 &lt;br /&gt;

    • 'full_html':使用 Full HTML 格式,避免过滤


2. 使用 htmlspecialchars_decode() 反转义 自己亲自做的OK 有大用

如果内容被转义成 &lt;br /&gt;,可以用 PHP 内置函数 htmlspecialchars_decode() 还原:

php
<?php print htmlspecialchars_decode($field_value); ?>
  • 适用场景:内容被 htmlspecialchars() 或 check_plain() 转义过

  • 示例

    php
    $text = "Line 1&lt;br /&gt;Line 2"; print htmlspecialchars_decode($text); // 输出:Line 1<br />Line 2

3. 使用 decode_entities()(Drupal 专用)

Drupal 的 decode_entities() 可以还原 HTML 实体:

php
<?php print decode_entities($field_value); ?>
  • 适用场景&lt;br /&gt;&amp;nbsp; 等实体被转义

  • 示例

    php
    $text = "First line&amp;nbsp;&lt;br /&gt;Second line"; print decode_entities($text); // 输出:First line <br />Second line

4. 在 Views 字段重写中强制解析

如果是在 Views 字段 中输出,可以在“重写结果”(Rewrite Results)中使用:

php
<?php print htmlspecialchars_decode($output); ?>

php
<?php print check_markup($output, 'full_html'); ?>

5. 检查输入格式(Filter Formats)

如果所有 <br /> 都被转义,可能是 输入格式 设置问题:

  1. 前往 admin/config/content/formats

  2. 检查使用的格式(如 Filtered HTML

  3. 取消勾选

  • ❌ Convert line breaks into HTML(如果内容已经含 <br />,不要重复转换)

  • ❌ Limit allowed HTML tags(可能过滤掉 <br />


总结

问题解决方案
&lt;br /&gt; 被转义输出<?php print htmlspecialchars_decode($text); ?>
数据库存储的内容含 HTML 实体<?php print decode_entities($text); ?>
Views 输出的字段被转义在重写中使用 check_markup($output, 'full_html')
全局 HTML 过滤太严格调整 admin/config/content/formats

使用 htmlspecialchars_decode() 或 check_markup() 是最直接的方法,确保 HTML 标签正常渲染。


普通分类: