Another one from the same project I used on titles, like link lists for posts with long titles.
Both of these came from a blog that had been custom and were thousands of posts. And the excerpt didn’t exist and the need to format single line titles. As well as some str replacing because there were numerous butchered incorrect encoding chars in the old posts (and breaks and new lines.. etc)
function shorten_copy($str, $len, $replace='', $cut=false){
// those special chars were fucking this up:
$from = array('“', 'â€', '‘', '’','\xE2\x80\x9C', '\xE2\x80\x9D',
'\xE2\x80\x9E', '\xE2\x80\x9F', '%e2%80%99', '%e2%80%9c', '%e2%80%9d');
$to = array('"', '"', "'", "'", '"', '"', '"', '"', "'", '"', '"');
$str = str_replace($from, $to, $str);
if(strlen($str)<=$len){
return $str.$replace;
}else{
$result = ($cut ? substr($str, 0, $len) : substr($str, 0, strrpos(substr($str, 0, $len), ' '))).$replace;
// just in case we end up with a wacky situation where the result === the replacement string. It happens on wordpress because of special chars.
// E.g. you can end up with strings like this: %e2%80%99Somethingreallylong%e2%80%9d which can end up being one string and turns into '...', i.e. the replacement string.
return ($result == $replace) ? substr($str, 0, $len) : $result;
}
}