php输出html时转义,该怎么处理

html-css014

php输出html时转义,该怎么处理,第1张

htmlspecialchars() 函数把预定义的字符转换为 HTML 实体。

语法:

htmlspecialchars(string,flags,character-set,double_encode)

预定义的字符是:

&(和号)成为 &amp

" (双引号)成为 &quot

' (单引号)成为 '

<(小于)成为 &lt

>(大于)成为 &gt

htmlspecialchars_decode() 函数把一些预定义的 HTML 实体转换为字符。

语法:

htmlspecialchars_decode(string,flags)

会被解码的 HTML 实体是:

&amp解码成 &(和号)

&quot解码成 " (双引号)

' 解码成 ' (单引号)

&lt解码成 <(小于)

&gt解码成 >(大于)

// 字符串反转义

function enXssHtml(text) {

const matchList = {

"<": "<",

">": ">",

"&": "&",

"": '""',

""": '"',

"'": "'",

}

let regStr = "(" + Object.keys(matchList).toString() + ")"

// ↑ ------------【 提取匹配列表key值 】.【组数转字符串】

regStr = regStr.replace(/,/g, ")|(")

// ↑ 通过匹配将其更新为正则的字符串类型

const regExp = new RegExp(regStr, "g")

// ↑ ------- 字符串 转 正则 方法

return text.replace(regExp, (match) =>matchList[match])

// ↑ ------ 替换方法 (正则, 当前key =>返回当前被匹配的key值)

}

// 字符串反转义

function deXssHtml(text) {

const matchList = {

"<": "<",

">": ">",

"&": "&",

'"': '"',

'"': '"',

"'": "'",

}

let regStr = "(" + Object.keys(matchList).toString() + ")"

// ↑ ------------【 提取匹配列表key值 】.【组数转字符串】

regStr = regStr.replace(/,/g, ")|(")

// ↑ 通过匹配将其更新为正则的字符串类型

const regExp = new RegExp(regStr, "g")

// ↑ ------- 字符串 转 正则 方法

return text.replace(regExp, (match) =>matchList[match])

// ↑ ------ 替换方法 (正则, 当前key =>返回当前被匹配的key值)

}