Last active
September 16, 2016 15:30
-
-
Save dewwwald/bad6342bac7a99b0728ab2c00934c47a to your computer and use it in GitHub Desktop.
This is an awesome html aware excerpt.
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 | |
/** | |
* @return string | |
*/ | |
function html_excerpt($string,$length=150,$ending="…") { | |
$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