Using PHP substr() and strip_tags() while retaining formatting and without breaking HTML

前端 未结 10 2087
Happy的楠姐
Happy的楠姐 2020-11-27 16:44

I have various HTML strings to cut to 100 characters (of the stripped content, not the original) without stripping tags and without breaking HTML.

Original H

10条回答
  •  迷失自我
    2020-11-27 17:36

    Here is my try at the cutter. Maybe you guys can catch some bugs. The problem, i found with the other parsers, is that they don't close tags properly and they cut in the middle of a word (blah)

    function cutHTML($string, $length, $patternsReplace = false) {
        $i = 0;
        $count = 0;
        $isParagraphCut = false;
        $htmlOpen = false;
        $openTag = false;
        $tagsStack = array();
    
        while ($i < strlen($string)) {
            $char = substr($string, $i, 1);
            if ($count >= $length) {
                $isParagraphCut = true;
                break;
            }
    
            if ($htmlOpen) {
                if ($char === ">") {
                    $htmlOpen = false;
                }
            } else {
                if ($char === "<") {
                    $j = $i;
                    $char = substr($string, $j, 1);
    
                    while ($j < strlen($string)) {
                        if($char === '/'){
                            $i++;
                            break;
                        }
                        elseif ($char === ' ') {
                            $tagsStack[] = substr($string, $i, $j);
                        }
                        $j++;
                    }
                    $htmlOpen = true;
                }
            }
    
            if (!$htmlOpen && $char != ">") {
                $count++;
            }
    
            $i++;
        }
    
        if ($isParagraphCut) {
            $j = $i;
            while ($j > 0) {
                $char = substr($string, $j, 1);
                if ($char === " " || $char === ";" || $char === "." || $char === "," || $char === "<" || $char === "(" || $char === "[") {
                    break;
                } else if ($char === ">") {
                    $j++;
                    break;
                }
                $j--;
            }
            $string = substr($string, 0, $j);
            foreach($tagsStack as $tag){
                $tag = strtolower($tag);
                if($tag !== "img" && $tag !== "br"){
                    $string .= "";
                }
            }
            $string .= "...";
        }
    
        if ($patternsReplace) {
            foreach ($patternsReplace as $value) {
                if (isset($value['pattern']) && isset($value["replace"])) {
                    $string = preg_replace($value["pattern"], $value["replace"], $string);
                }
            }
        }
        return $string;
    }
    

提交回复
热议问题