protected function TruncateHTML::domNodeTruncateWords in Smart Trim 8
Truncates a DOMNode by words.
Parameters
\DOMNode $domnode: Object to be truncated.
1 call to TruncateHTML::domNodeTruncateWords()
- TruncateHTML::truncateWords in src/
Truncate/ TruncateHTML.php - Truncates HTML text by words.
File
- src/
Truncate/ TruncateHTML.php, line 201 - Contains trim functionality.
Class
- TruncateHTML
- Class TruncateHTML.
Namespace
Drupal\smart_trim\TruncateCode
protected function domNodeTruncateWords(\DOMNode $domnode) {
foreach ($domnode->childNodes as $node) {
if ($this->foundBreakpoint == TRUE) {
return;
}
if ($node
->hasChildNodes()) {
$this
->domNodeTruncateWords($node);
}
else {
$cur_count = $this
->countWords($node->nodeValue);
if ($this->wordCount + $cur_count >= $this->limit) {
// We have found our end point.
if ($cur_count > 1 && $this->limit - $this->wordCount < $cur_count) {
// Note that PREG_SPLIT_OFFSET_CAPTURE and UTF-8 is interesting.
// preg_split() works on the string as an array of bytes therefore
// in order to use it's results we need to use non unicode aware
// functions.
// @see https://bugs.php.net/bug.php?id=67487
$words = preg_split("/[\n\r\t ]+/", $node->nodeValue, $this->limit - $this->wordCount + 1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
end($words);
$last_word = prev($words);
$node->nodeValue = substr($node->nodeValue, 0, $last_word[1] + strlen($last_word[0]));
}
$this
->removeTrailingPunctuation($node);
$this
->removeProceedingNodes($node);
$this
->insertEllipsis($node);
$this->foundBreakpoint = TRUE;
return;
}
else {
$this->wordCount += $cur_count;
}
}
}
}