[6782] | 1 | <?php |
---|
| 2 | // Author prajwala |
---|
| 3 | // email m.prajwala@gmail.com |
---|
| 4 | // Date 12/04/2009 |
---|
| 5 | // version 1.0 |
---|
| 6 | |
---|
| 7 | class HtmlCutString{ |
---|
[9572] | 8 | function __construct($string, $limit){ |
---|
| 9 | // create dom element using the html string |
---|
| 10 | $this->tempDiv = new DomDocument; |
---|
| 11 | $this->tempDiv->loadXML('<div>'.$string.'</div>'); |
---|
| 12 | // keep the characters count till now |
---|
| 13 | $this->charCount = 0; |
---|
| 14 | $this->encoding = 'UTF-8'; |
---|
| 15 | // character limit need to check |
---|
| 16 | $this->limit = $limit; |
---|
[6782] | 17 | } |
---|
[9572] | 18 | function cut(){ |
---|
| 19 | // create empty document to store new html |
---|
| 20 | $this->newDiv = new DomDocument; |
---|
| 21 | // cut the string by parsing through each element |
---|
| 22 | $this->searchEnd($this->tempDiv->documentElement,$this->newDiv); |
---|
| 23 | $newhtml = $this->newDiv->saveHTML(); |
---|
| 24 | return $newhtml; |
---|
[6782] | 25 | } |
---|
[9572] | 26 | function deleteChildren($node) { |
---|
| 27 | while (isset($node->firstChild)) { |
---|
| 28 | $this->deleteChildren($node->firstChild); |
---|
| 29 | $node->removeChild($node->firstChild); |
---|
| 30 | } |
---|
| 31 | } |
---|
| 32 | function searchEnd($parseDiv, $newParent){ |
---|
| 33 | foreach($parseDiv->childNodes as $ele){ |
---|
| 34 | // not text node |
---|
| 35 | if($ele->nodeType != 3){ |
---|
| 36 | $newEle = $this->newDiv->importNode($ele,true); |
---|
| 37 | if(count($ele->childNodes) === 0){ |
---|
| 38 | $newParent->appendChild($newEle); |
---|
| 39 | continue; |
---|
| 40 | } |
---|
| 41 | $this->deleteChildren($newEle); |
---|
| 42 | $newParent->appendChild($newEle); |
---|
| 43 | $res = $this->searchEnd($ele,$newEle); |
---|
| 44 | if($res) |
---|
| 45 | return $res; |
---|
| 46 | else |
---|
| 47 | continue; |
---|
| 48 | } |
---|
| 49 | // the limit of the char count reached |
---|
| 50 | if(mb_strlen($ele->nodeValue,$this->encoding) + $this->charCount >= $this->limit){ |
---|
| 51 | $newEle = $this->newDiv->importNode($ele); |
---|
| 52 | $newEle->nodeValue = substr($newEle->nodeValue,0, $this->limit - $this->charCount); |
---|
| 53 | $newParent->appendChild($newEle); |
---|
| 54 | return true; |
---|
| 55 | } |
---|
| 56 | $newEle = $this->newDiv->importNode($ele); |
---|
| 57 | $newParent->appendChild($newEle); |
---|
| 58 | $this->charCount += mb_strlen($newEle->nodeValue,$this->encoding); |
---|
| 59 | } |
---|
| 60 | return false; |
---|
| 61 | } |
---|
[6782] | 62 | } |
---|
| 63 | ?> |
---|