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_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.
ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED Replace 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_HTML401 Handle code as HTML 4.01.
ENT_XML1 Handle code as XML 1.
ENT_XHTML Handle code as XHTML.
ENT_HTML5 Handle 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;
}




你可能感兴趣的:(PHP & Javascript 如何对字符串中包含html标签进行编码 整理)