PHP 4.x 內建 fgetss() 無法完整過濾 HTML 標籤,尤其在標籤跨行或包含特殊字元時失效。作者分析缺陷並提供替代函數 mygets()。
<?php
$fp = fopen("index.html", "r");
while (!feof($fp)) {
$ms = fgetss($fp);
printf($ms);
}
fclose($fp);
?>
<?php
function mygets($myFile) {
$myline = fgets($myFile, 255);
$big = strlen(strstr($myline, ">"));
$small = strlen(strstr($myline, "<"));
if ($big > $small) { // 處理標籤中間換行情況
$myline = strstr($myline, ">");
$myline = substr($myline, 1);
}
$len = strlen($myline);
$startskip = false;
$outstring = "";
for ($i = 1; $i <= $len; $i++) {
$a = substr($myline, $i-1, 1);
switch ($a) {
case "<": $startskip = true; break;
case ">": $startskip = false; break;
default: break;
}
if (!$startskip && $a != ">") $outstring .= $a;
}
$outstring = str_replace(" ", " ", $outstring);
$outstring = str_replace(" ", "", $outstring); // 半形空格
$outstring = str_replace(" ", "", $outstring); // 全形空格
return $outstring;
}
?>
< 進入跳過模式,遇到 > 結束跳過。>(跨行標籤情況)。 、半形/全形空白。免費使用,歡迎改進。