Site icon Web Niraj

PHP Substring – Respecting the Last Word

Sometimes, you want to truncate a string to a given length, but keep the last word of the string intact. For example, reducing the string “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt” to 35 characters, but we don’t want any word to be cut-off.

The following function does exactly that…

function substr_word( $string, $len = 35 ) {
    return substr( ( $str = wordwrap( $string, $len, '$$' ) ), 0, strpos( $str, '$$' ) );
}

This function would reduce the above string to “Lorem ipsum dolor sit amet,”. The word “consectetur” falls in the cut off point, but instead of cutting off the word, the string is reduced to the end of the previous word.

Exit mobile version