source: extensions/ContestResults/include/cutstring.class.php @ 6782

Last change on this file since 6782 was 6782, checked in by mistic100, 14 years ago

Fixs some errors. Add results previews. Code revision.

File size: 1.8 KB
Line 
1<?php
2// Author prajwala
3// email  m.prajwala@gmail.com
4// Date   12/04/2009
5// version 1.0
6
7class HtmlCutString{
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;
17  }
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;
25  }
26
27  function deleteChildren($node) {
28    while (isset($node->firstChild)) {
29      $this->deleteChildren($node->firstChild);
30      $node->removeChild($node->firstChild);
31    }
32  } 
33  function searchEnd($parseDiv, $newParent){
34    foreach($parseDiv->childNodes as $ele){
35        // not text node
36        if($ele->nodeType != 3){
37          $newEle = $this->newDiv->importNode($ele,true);
38          if(count($ele->childNodes) === 0){
39            $newParent->appendChild($newEle);
40            continue;
41          }
42          $this->deleteChildren($newEle);
43          $newParent->appendChild($newEle);
44            $res = $this->searchEnd($ele,$newEle);
45            if($res)
46                        return $res;
47            else
48                        continue;
49        }
50
51        // the limit of the char count reached
52        if(mb_strlen($ele->nodeValue,$this->encoding) + $this->charCount >= $this->limit){
53          $newEle = $this->newDiv->importNode($ele);
54            $newEle->nodeValue = substr($newEle->nodeValue,0, $this->limit - $this->charCount);
55            $newParent->appendChild($newEle);
56            return true;
57        }
58        $newEle = $this->newDiv->importNode($ele);
59        $newParent->appendChild($newEle);
60        $this->charCount += mb_strlen($newEle->nodeValue,$this->encoding);
61    }
62    return false;
63  }
64}
65?>
Note: See TracBrowser for help on using the repository browser.