/ Published in: PHP
URL: http://www.phpclasses.org/browse/file/26823.html
In PHP, it is easy to extract an excerpt of a text string with a given length limit. But if you want to extract an excerpt from HTML, the tags that may exist in the text string make it more complicated.
This class provides a solution to extract excerpts from HTML documents with a given text length limit without counting the length of any HTML tags.
Expand |
Embed | Plain Text
<?php /* In PHP, it is easy to extract an excerpt of a text string with a given length limit. But if you want to extract an excerpt from HTML, the tags that may exist in the text string make it more complicated. This class provides a solution to extract excerpts from HTML documents with a given text length limit without counting the length of any HTML tags. */ // Author prajwala // email [email protected] // Date 12/04/2009 // version 1.0 class HtmlCutString{ function __construct($string, $limit){ // create dom element using the html string $this->tempDiv = new DomDocument; $this->tempDiv->loadXML('<div>'.$string.'</div>'); // keep the characters count till now $this->charCount = 0; $this->encoding = 'UTF-8'; // character limit need to check $this->limit = $limit; } function cut(){ // create empty document to store new html $this->newDiv = new DomDocument; // cut the string by parsing through each element $this->searchEnd($this->tempDiv->documentElement,$this->newDiv); $newhtml = $this->newDiv->saveHTML(); return $newhtml; } function deleteChildren($node) { $this->deleteChildren($node->firstChild); $node->removeChild($node->firstChild); } } function searchEnd($parseDiv, $newParent){ foreach($parseDiv->childNodes as $ele){ // not text node if($ele->nodeType != 3){ $newEle = $this->newDiv->importNode($ele,true); $newParent->appendChild($newEle); continue; } $this->deleteChildren($newEle); $newParent->appendChild($newEle); $res = $this->searchEnd($ele,$newEle); if($res) return $res; else{ continue; } } // the limit of the char count reached $newEle = $this->newDiv->importNode($ele); $newParent->appendChild($newEle); return true; } $newEle = $this->newDiv->importNode($ele); $newParent->appendChild($newEle); } return false; } } function cut_html_string($string, $limit){ $output = new HtmlCutString($string, $limit); return $output->cut(); } ?>
You need to login to post a comment.
