php过滤html标签截取部分内容 - 防空洞123

时间:2024-02-22 09:04:07

php过滤html标签截取部分内容

<?php

$str = \'<span>fdsfsdf</span><a href="#">href</a>\';
echo htmlspecialchars($str).\'<Br>\';
echo strip_tags($str);

?>

用strip_tags能把Html标签都去掉,然后调用truncate函数
$array[$row[\'content_id\']][\'content_title\']=truncate(strip_tags($row[\'content_title\']),21);
function truncate($string,$length,$append = true){
    $string = trim($string);
    $strlength = strlen($string);
    if ($length == 0 || $length >= $strlength){
        return $string;
    }elseif ($length < 0){
        $length = $strlength + $length;
        if ($length < 0)
        {
            $length = $strlength;
        }
    }
    if (function_exists(\'mb_substr\')){
        $newstr = mb_substr($string, 0, $length,"UTF-8");
    }elseif (function_exists(\'iconv_substr\')){
        $newstr = iconv_substr($string, 0, $length,"UTF-8");
    }else{
      for($i=0;$i<$length;$i++){
            $tempstring=substr($string,0,1);
            if(ord($tempstring)>127){
               $i++;
               if($i<$length){
                  $newstring[]=substr($string,0,3);
                  $string=substr($string,3);
               }
            }else{
               $newstring[]=substr($string,0,1);
               $string=substr($string,1);
            }
         }
      $newstr =join($newstring);
    }
    if ($append && $string != $newstr){
        $newstr .= \'...\';
    }
    return $newstr;
}