比方说,我有一个来自用户的字符串($input
)。我可以去,strip tags,只允许允许标签。我可以转换为文本htmlspecialchars()
。我甚至可以用文本替换我不想要的所有标签。解析HTML用户输入
function html($input) {
$input = '<bl>'.htmlspecialchars($input).'</bl>'; // bl is a custom tag that I style (stands for block)
global $open;
$open = []; //Array of open tags
for ($i = 0; $i < strlen($input); $i++) {
if (!in_array('code', $open) && !in_array('codebl', $open)) { //If we are parsing
$input = preg_replace_callback('#^(.{'.$i.'})<(em|i|del|sub|sup|sml|code|kbd|pre|codebl|quote|bl|sbl)>\s*#s', function($match) {
global $open; //...then add new tags to the array
array_push($open,$match[2]);
return $match[1].'<'.$match[2].'>'; //And replace them
}, $input);
$input = preg_replace_callback('#^(.{'.$i.'})(https?):\/\/([^\s"\(\)<>]+)#', function($m) {
return $m[1].'<a href="'.$m[2].'://'.$m[3].'" target="_blank">'.$m[3].'</a>';
}, $input, -1, $num); //Simple linking
$i += $num * 9;
$input = preg_replace_callback('#^(.{'.$i.'})\n\n#', function($m) {
return $m[1].'</bl><bl>';
}, $input); // More of this bl element
}
if (end($open)) { //Close tags
$input = preg_replace_callback('#^(.{'.$i.'})</('.end($open).')>#s', function($match) {
global $open;
array_pop($open);
return trim($match[1]).'</'.$match[2].'>';
}, $input);
}
}
while ($open) { //Handle unclosed tags
$input .= '</'.end($open).'>';
array_pop($open);
}
return $input;
}
的问题是,在这之后,有没有办法写字面上<i&lgt;</i>
,因为它会自动解析到任何<i></i>
(如果你写<i></i>
),或&lt;i&gt;&lt;/i&gt;
(如果你写<i></i>
)。我希望用户能够输入<
(或任何其他HTML实体)并获得<
。如果我只是直接发送给浏览器,那么它显然会受到黑客正在尝试的任何魔术(以及我放)的影响。那么,我该如何让用户使用任何预先定义的HTML标记集,同时让它们使用html实体?
改为使用HTMLPurifier。 striptags是核弹,htmlpurifier可以是手术刀(但也支持核武器)。 –
@MarcB哦......闪亮! – bjb568
看这个链接 [stackoverflow.com] [1] [stackoverflow.com] [2] [1]:http://stackoverflow.com/questions/ 1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 [2]:http://stackoverflow.com/questions/3577641/how-do-you-parse-and -process-html-xml-in-php – Mortzea