Html实体用php返回特殊字符

发布于 2024-12-17 16:36:20 字数 394 浏览 6 评论 0原文

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

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

我现在能做什么?

我的代码如下所示:

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

I want to convert special characters to HTML entities, and then back to the original characters.

I have used htmlentities() and then html_entity_decode(). It worked fine for me, but { and } do not come back to the original characters, they remain { and }.

What can I do now?

My code looks like:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身软味 2024-12-24 16:36:20

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

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

演示(点击右上角的“源”链接)

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

"{hello}"

htmlentities 的调用将 & 编码为 &,这会为您提供字符串

"&#123;hello}"

The & 然后被解码回 &,输出:

"{hello}"

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

$custom_header = "{hello}";
$custom_header = htmlentities($custom_header);

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

Even though nobody can replicate your problem, here's a direct way to solve it by a simple str_replace.

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

Demo (click the 'Source' link in the top right)

Edit: I see the problem now. If your input string is:

"{hello}"

A call to htmlentities encodes the & into &, which gives you the string

"&#123;hello}"

The & is then later decoded back into &, to output this:

"{hello}"

The fix is to send the string through html_entity_decode again, which will properly decode your entities.

$custom_header = "{hello}";
$custom_header = htmlentities($custom_header);

$custom_header = html_entity_decode($custom_header);
echo html_entity_decode( $custom_header); // Outputs {hello}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文