Skip to content

Instantly share code, notes, and snippets.

@dewwwald
Last active September 16, 2016 15:30
Show Gist options
  • Save dewwwald/bad6342bac7a99b0728ab2c00934c47a to your computer and use it in GitHub Desktop.
Save dewwwald/bad6342bac7a99b0728ab2c00934c47a to your computer and use it in GitHub Desktop.
This is an awesome html aware excerpt.
<?php
/**
* @return string
*/
function html_excerpt($string,$length=150,$ending="&hellip;") {
$opening_regex = '/((?:<[a-zA-Z0-9="\':.,;\-() ]*>)*)(.*)/';
$closing_regex = '/(<\/[a-zA-Z0-9="\':.,;\-() ]*>)/';
$string = trim($string);
$str_len = 0;
$new_string = '';
$c = 0;
do {
preg_match($opening_regex, $string, $matches);
preg_match($closing_regex, $matches[2], $closing_tag_string);
$split = preg_split($closing_regex, $matches[2], 2);
$append = "";
if ((strlen($split[0]) + $str_len) < $length)
{
$actual_string = $split[0];
}
else
{
$actual_string = substr($split[0], 0, $length - (strlen($split[0]) + $str_len));
}
$append = $matches[1].$actual_string.$closing_tag_string[0].$split[1];
$new_string = $new_string.$append;
$str_len += strlen($actual_string);
$string = substr($string, strlen($append)-1);
$string = trim($string);
$c++;
} while ($str_len < $length);
return trim($new_string).$ending;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment