Skip to content

Instantly share code, notes, and snippets.

@morganney
Last active November 25, 2017 12:22
Show Gist options
  • Save morganney/8250557 to your computer and use it in GitHub Desktop.
Save morganney/8250557 to your computer and use it in GitHub Desktop.
HTML Excerpt with PHP
<?php
// requires PHP >= 5.3.6 to support saveHTML([$node])
function getPostPreview($html, $num_chars) {
if(strlen($html) <= $num_chars) $preview = $html;
else {
$preview = '';
$dom = $DOMDocument::loadHTML($html); // creates DOCTYPE, <html>, and <body>
$dom->removeChild($dom->firstChild); // DOCTYPE
/*
* If your post is wrapped by a parent element with an id:
* $node = $dom->getElementById('id')->firstChild
* Otherwise skip <html> and <body> and grab the first element of your post
*/
$node = $dom->firstChild->firstChild->firstChild;
while(strlen($preview) < $num_chars) {
$preview .= $dom->saveHTML($node);
$node = $node->nextSibling;
}
}
return $preview;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment