Skip to content

Instantly share code, notes, and snippets.

@chaance
Last active July 24, 2018 01:42
Show Gist options
  • Save chaance/cc3007ca635497caafd256e5399e4b3d to your computer and use it in GitHub Desktop.
Save chaance/cc3007ca635497caafd256e5399e4b3d to your computer and use it in GitHub Desktop.
Truncate a string to a maximum number of characters to the nearest complete word.
<?php
/**
* Truncate a string to a maximum number of characters to the nearest complete word.
*
* @param string $string String to truncate.
* @param int $max_char_width Maximum number of characters.
* @param string $append New string to append at the end of the truncated string.
* @return string Truncated string.
*/
function truncate_string( $string = '', $max_char_width = 200, $append = '' ) {
if ( empty( $string ) ) {
return;
}
$parts = preg_split( '/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE );
$parts_count = count( $parts );
$length = 0;
for ( $last_part = 0; $last_part < $parts_count; $last_part++ ) {
$length += strlen( $parts[ $last_part ] );
if ( $length > $max_char_width ) {
break;
}
}
$new_string = trim( implode( array_slice( $parts, 0, $last_part ) ) );
if ( ! empty( $append ) && ! empty( $new_string ) ) {
// Remove ending punctuation before appending.
$new_string = preg_replace( '/[0-9.!?,;:]$/', '', $new_string ) . $append;
}
return $new_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment