PHP & Javascript 如何对字符串中包含html标签进行编码 整理

为什么要对字符串编码?


某些字符串中包含html标签,不编码,页面输出就乱了。


PHP下怎么对字符串编码?


htmlentities vs htmlspecialchars

htmlentities 与htmlspecialchar 区别:

htmlentities is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

除了不加参数直接调用htmlentities()以外,这2个function是等价的。

不加参数直接调用htmlentities()时,会把输入的字符串全部当作html标签去编码,所以会产生乱码。

htmlspecialchars只处理这几种字符:

  • '&' (ampersand) becomes '&'
  • '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

都支持同样的编码参数:

ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.
ENT_IGNORESilently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTEReplace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWEDReplace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401Handle code as HTML 4.01.
ENT_XML1Handle code as XML 1.
ENT_XHTMLHandle code as XHTML.
ENT_HTML5Handle code as HTML 5.
参考: 点击打开链接http://php.net/manual/zh/function.htmlentities.php

点击打开链接http://php.net/manual/zh/function.htmlspecialchars.php

javascript 中怎么对字符串编码?

js中只有 encodeURI()encodeURIComponent()escape()

前两个只对uri编码,后一个编码范围太大

参考: 点击打开链接http://www.w3school.com.cn/jsref/jsref_encodeURIComponent.asp

点击打开链接http://www.w3school.com.cn/jsref/jsref_encodeURIComponent.asp

为什么要对URI编码?

参考:http://www.cnblogs.com/leaven/archive/2012/07/12/2588746.html点击打开链接

js中如何对包含html标签字符串编码,一般做法:

function html_encode(str) {
	var s = "";
	if (str.length == 0) return "";
	s = str.replace(/&/g, ">");
	s = s.replace(/</g, "<");
	s = s.replace(/>/g, ">");
	s = s.replace(/ /g, " ");
	s = s.replace(/\'/g, "'");
	s = s.replace(/\"/g, """);
	s = s.replace(/\n/g, "<br>");
	return s;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值