Last active
November 25, 2017 12:22
-
-
Save morganney/8250557 to your computer and use it in GitHub Desktop.
HTML Excerpt with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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