Skip to content

Instantly share code, notes, and snippets.

@dfadler
Last active October 4, 2015 03:18
Show Gist options
  • Save dfadler/2568485 to your computer and use it in GitHub Desktop.
Save dfadler/2568485 to your computer and use it in GitHub Desktop.
PHP String Truncation
<?php
/**
* Truncates a string to be no more than $numwords. **Will work with html if $strip_html is true**
* @param string $input The string to be truncated
* @param int $numwords The number of words to be returned
* @param string $padding Ellipsis...
* @param boolean $strip_html Should be set to true if html is contained within $input
* @return string The truncated string
*/
function truncate_string($input, $numwords, $padding="...", $strip_html=false) {
$tmp = explode(' ', $input);
$count_word = sizeof($tmp);
if($strip_html == true){
if($count_word > $numwords) {
ob_start();
echo $input;
$old_input = ob_get_clean();
$new_input = strip_tags($old_input);
$output = strtok($new_input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
if($output != $new_input) $output .= $padding;
return $output;
} else {
ob_start();
echo $input;
$old_input = ob_get_clean();
$new_input = strip_tags($old_input);
$output = strtok($new_input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
return $output;
}
} else {
if($count_word > $numwords) {
$output = strtok($input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
if($output != $input) $output .= $padding;
return $output;
} else {
$output = strtok($input, " \n");
while(--$numwords > 0) $output .= " " . strtok(" \n");
return $output;
}
}
}
/**
* Truncates $input to a character $length
* @param string $input The string to be truncated
* @param int $length The character length to be truncated to
* @param string $elipsis ...
* @return string The truncated $input
*/
function truncate_string_character($input, $length, $elipsis='...') {
if(strlen($input) > $length):
$output = substr($input, 0, $length);
$output .= $elipsis;
return $output;
else:
return $input;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment