比方說,我有一個來自用戶的字符串($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