Skip to content

Instantly share code, notes, and snippets.

@fitzage
Last active October 9, 2015 08:37
Show Gist options
  • Save fitzage/3470731 to your computer and use it in GitHub Desktop.
Save fitzage/3470731 to your computer and use it in GitHub Desktop.
Kirby plugin to truncate by number of words and preserve tags. Works with Kirby v2.
<?php
function truncate($input, $numwords, $padding="")
{
$output = strtok($input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
if($output != $input) $output .= $padding;
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
$opened = array();
// loop through opened and closed tags in order
if(preg_match_all("/<(\/?[a-z]+)>?/i", $output, $matches)) {
foreach($matches[1] as $tag) {
if(preg_match("/^[a-z]+$/i", $tag, $regs)) {
// a tag has been opened
if(strtolower($regs[0]) != 'br') $opened[] = $regs[0];
} elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) {
// a tag has been closed
$array_keys = array_keys($opened, $regs[1]);
unset($opened[array_pop($array_keys)]);
}
}
}
// close tags that are still open
if($opened) {
$tagstoclose = array_reverse($opened);
foreach($tagstoclose as $tag) $output .= "</$tag>";
}
return $output;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment