duankeng2026
2015-09-06 03:12
浏览 168
已采纳

使用textarea中的htmlentities转义HTML,但转回HTML用于数据库

So I have slight problem. The PHP program I am working on allows web designers to post some code sometimes, and is put into a backend database. Sometimes the designers may also want to discuss html entities.

So let's say the designer adds a line of code to database like this:

<p>hellos friend</p>

So I use PDO to stick this line in the database without escaping it, and everything is fine, it shows up good. Now, I want the web designer to be able to edit this, so when I pull it out of database I use this code after:

$post = htmlentities($post);

It is good now that I can insert this into my editor:

<textarea>$post</textarea>

But we have problem because when this guy edit this code, he submit and it go back into the database and now it got HTML entities and has & lt ; instead of < and & gt ; instead of > (it is hard to type this on SA it re-encodes it)

&lt;p&gt;hellos friend&lt;/p&gt;

So now it's wrong in database, so when I display it again, it show the entities.

So maybe I can run the opposite of htmlentities after editing it and re-add all the entities, if there is such a thing, but that brings another problem:

What if a web designer is telling other guy "Hey man, this is what an html entity is, it is typed like this: & lt; you should use it"

Then THAT is going to turn out to get stuck back into NOT being an entity, you see what I mean? Is there a solute?

图片转代码服务由CSDN问答提供 功能建议

所以我有一点问题。 我正在开发的PHP程序允许Web设计人员有时发布一些代码,并放入后端数据库。 有时候设计师也可能想讨论html实体。

所以我们假设设计师在数据库中添加了一行代码:

 &lt; p&gt; hellos friend&lt; / p&gt; 
   
 
 

所以我使用PDO将这一行粘在数据库中而不转义它,一切都很好,它显示 很好。 现在,我希望网页设计师能够编辑它,所以当我从数据库中取出它时,我会在以下代码后使用此代码:

  $ post = htmlentities($ post)  ; 
   
 
 

现在好了,我可以将它插入我的编辑器中:

 &lt; textarea&gt; $  post&lt; / textarea&gt; 
   
 
 

但是我们遇到了问题,因为当这个人编辑这段代码时,他提交并返回数据库,现在它获得了HTML实体和 有&amp; lt; 而不是&lt; 和&amp; gt; 而不是&gt; (很难在SA上输入它重新编码)

 &amp; lt; p&amp; gt; hellos friend&amp; lt; / p&amp; gt; 
 <  / code>  
 
 

所以现在它在数据库中是错误的,所以当我再次显示它时,它会显示实体。

所以也许我可以运行 在编辑它之后反对 htmlentities ,并重新添加所有实体,如果有这样的事情,但这带来了另一个问题:

如果网页设计师怎么办? 正在告诉其他人“嘿,这是一个html实体,它是这样输入的:&amp; lt; 你应该使用它” \ n

那么结果会被卡回到不是一个实体,你明白我的意思了吗? 有解决方案吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanla8800 2015-09-06 05:34
    已采纳

    I think you are looking for the html_entity_decode() function. It is the reverse of htmlentities(). It converts the &lt back into <

    http://php.net/manual/en/function.html-entity-decode.php

    For your second issue you would need to have the designers escape the html entities somehow. I don't think PHP has a way to escape them but I could be wrong. It might be something you would have to implement yourself, like have the designer put a \ in front of the entity to set it apart from the entities that are suppose to be converted to HTML and then parse the input looking for escaped entities.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题