【问题标题】:Html entities back to special characters with phphtml实体回用php特殊字符
【发布时间】:2011-11-23 02:12:16
【问题描述】:

我想将特殊字符转换为 HTML 实体,然后再转换回原始字符。

我使用了htmlentities(),然后是html_entity_decode()。它对我来说效果很好,但 { 和 } 不会回到原来的字符,它们仍然是 { 和 }。

我现在能做什么?

我的代码如下:

$custom_header = htmlentities($custom_header);
$custom_header = html_entity_decode($custom_header);

【问题讨论】:

  • 无法复制。 codepad.org/EpUQzjrx 请提供一个完整的示例来演示此行为。
  • 我的 $custom_header 看起来像这样

  • 所以您正在对包含{ 的字符串进行htmlentity 编码,并在解码时返回{?这是……预料之中的。
  • 请点击链接codepad.org/EpUQzjrx,帮我一个忙。我想要 {到 '{' 否则我的 jquery 代码不起作用。
  • 看起来是完全相同的字符串,请看这个输出 bin2hex 的粘贴 '{}': codepad.org/IvdErNzg

标签: php html-entities html-encode


【解决方案1】:

即使没有人可以复制您的问题,这里有一个直接的方法可以通过简单的str_replace 来解决它。

$input = '<p><script type="text/javascript"> $(document).ready(function() &#123; $("#left_side_custom_image").click(function() &#123; alert("HELLO"); &#125;); &#125;); </script></p> ';
$output = str_replace( array( '&#123;', '&#125;'), array( '{', '}'), $input);

Demo(点击右上角的“来源”链接)

编辑:我现在看到了问题。如果您的输入字符串是:

"&#123;hello}"

对htmlentities 的调用会将&amp;amp; 编码为&amp;amp;,从而为您提供字符串

"&amp;#123;hello}"

&amp;amp; 随后被解码回&amp;amp;,以输出:

"&#123;hello}"

解决方法是再次通过html_entity_decode 发送字符串,这将正确解码您的实体。

$custom_header = "&#123;hello}";
$custom_header = htmlentities($custom_header);

$custom_header = html_entity_decode($custom_header);
echo html_entity_decode( $custom_header); // Outputs {hello}

【讨论】:

  • 感谢您的回答,但如果任何其他字符包含稍后,这一次不是?如何编写此类字符的完整替换代码?
  • @user1044804 - 我已经编辑了我的解决方案,为您最近的粘贴添加了修复。
猜你喜欢
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 2019-03-20
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
相关资源
最近更新 更多