Skip to content

Instantly share code, notes, and snippets.

@prochor666
Last active August 29, 2015 14:07
Show Gist options
  • Save prochor666/252c6814cf299c0a26d8 to your computer and use it in GitHub Desktop.
Save prochor666/252c6814cf299c0a26d8 to your computer and use it in GitHub Desktop.
Cut string, reflect words delimited by space, cuts some ugly chars from the end
<?php
/**
* Cut string, reflect words delimited by space, cuts some ugly chars from the end
* @param string $str
* @param int $length
* @return string
*/
function cutStr($str, $length = 255, $suffix = NULL){
// printable, formal, to samy co nad tim, jen jinak psany
// $str = mb_ereg_replace( '[^[:print:]]', '', self::autoUTF( $str ) );
$str = trim(strip_tags($str));
$str = trim($str, ',.');
if (mb_strlen($str)<=$length) {
return $str;
}
$str = mb_substr($str, 0, $length);
$pos = mb_strrpos($str, " ");
$str = $pos>1 ? mb_substr( $str, 0, $pos ): $str;
$str = trim($str, '-, ');
// short last word
$wordLimit = 4;
$words = explode( ' ', $str );
$lastPos = count( $words ) - 1;
$lastWordLength = mb_strlen( $words[$lastPos] );
if( $lastWordLength < $wordLimit ){
$str = mb_substr( $str, 0, -($lastWordLength+1) );
}
return $str.$suffix;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment