I'm trying to truncate a long string to a specific number of characters and interpolate another user-defined string in the middle of it (more or less) to represent that the string has been truncated. And at at same time, I'm trying to make the words to not get broken in half. E.g:
The quick brown fox jumped over the lazy dog
If defined (as function parameter) to truncate this string to 20 characters the resulting string should be something like:
The quick brown ... the lazy dog
The closest implementation I came was:
function truncate( $string, $length, $append = NULL ) { if( strlen( $string ) <= $length ) return $string; $append = ( strlen( $append ) ? sprintf( ' %s ', $append ) : ' ... ' ); $start = round( $length / 2 ); $start = strlen( substr( $string, 0, ( strpos( substr( $string, $start ), ' ' ) + $start ) ) ); $end = ( $start - strlen( $append ) ); $end = strlen( substr( $string, 0, strrpos( substr( $string, $start + strlen( $append ) - 1 ), ' ' ) ) ); return substr( $string, 0, $start ) . $append . substr( $string, ( strlen( $string ) - $end ) ); } But not only this is not running smoothly with strings of different lengths, but it's also not truncating to the size as defined.
For some strings I'm receiving duplicated blank characters (because of wrong math about the blank spaces used by sprintf() over $append), sometimes one letter is removed from the word closest to the interpolated string and sometimes a word is getting broken in half when it shouldn't.
The above string, for example, if used like:
truncate( $str, 20 ); Results in:
The quick brown ... ped over the lazy dog
"The quick...lazy dog"?