LINUX.ORG.RU

php реализация ката


0

2

Есть код в нём из базы выдирается текст с html тегами Иногда очень большой текст получается, как его красиво обрезать например после 200 слова, именно слова а не символа, а ещё учитывать чтобы теги не разрывались?

★★★

        function cuttext($html,$len)
        {
                $clean=preg_replace("/(<\/?)(\w+)([^>]*>)/", " ", $html);
                if (strlen($clean)<$len) return $html;
                $clean=explode(" ",$clean);
                $i=0;
                $j=0;
                $pos=0;
                $word=null;
                while ($i<=$len and isset($clean[$j]))
                {
                        $word=$clean[$j];
                        $pos=$j;
                        $i+=strlen($clean[$j])+1;
                        $j++;
                }
                foreach ($clean as $key=>$value){

                        if ($word!=$value){
                                unset($clean[$key]);
                        }
                }
                foreach ($clean as $key=>$value){

                        if ($pos<$key){
                                unset($clean[$key]);
                        }
                }
                //print_r($word);
                $iFrom = 0;
                $iLoop = 0;
                do
                {
                        $pos = strpos($html,$word,$iFrom);
                        $iFrom = $pos + strlen($word);
                }
                while ((++$iLoop)<count($clean));

                $len=$iFrom;
                $start=substr($html,0,$len);
                $end=substr($html,$len);
                $gtp=strrpos($start,">");
                $ltp=strrpos($start,"<");
                if ($gtp<$ltp)
                {
                        $cut=substr($start,$ltp);
                        $start=substr($start,0,$ltp);
                        $end=$cut.$end;
                }
                //put all opened tags into an array
                preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU",$end,$result);
                $openedtags=$result[1];
                //put all closed tags into an array
                preg_match_all("#</([a-z]+)>#iU",$end,$result);
                $closedtags=$result[1];

                $res=array_diff($closedtags,$openedtags);
                foreach ($res as $tag)
                $start.="</".$tag.">";
                return $start;
        }

Надеюсь суть этого быдлокода понятна.

iSage ★★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.