Skip to content Skip to sidebar Skip to footer

Html Errors When Truncating?

I have the following function: function truncate($string, $limit, $break='.', $pad='...') { if(strlen($string) <= $limit) return $string; if(false !== ($breakpoint = str

Solution 1:

Don't truncate the $html but rather the real text where it's appropriate. To get hold of the text, you could use php's xml functions (DOM, SimpleXml) or regular expression. Though I'd advice the first.

Example using Dom:

$html = '<div style="bla: bla;">somet30ext</div> <div id="bla">MORE AND MORE TEXT</div>';

$dom = new DomDocument;
$dom->loadHtml($html);

$xpath = new DomXpath($dom);

// example of getting a div with id=bla$bla = $xpath->query('//div[@id="bla"]')->item(0);
if ($blainstanceof DomNode) {

  // truncate hereif (strlen($bla->nodeValue) > 10) {
    $bla->nodeValue = substr($bla->nodeValue, 0, 10) . '...';
  }
}

// collect result, this is needed due to dom->loadhtml wrapping the loaded string// with html/body if not present$result = '';
foreach ($xpath->query('//body/*') as$childNode) {
  $result .= $dom->saveHtml($childNode);
}

echo$result;

Solution 2:

Well, in truncate function just look for opening tags, count them, and look for these tags to close, when all are closed that's is your string.

Post a Comment for "Html Errors When Truncating?"