Skip to content

Instantly share code, notes, and snippets.

@artikus11
Last active July 22, 2021 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artikus11/dfe4e573204cae3d11e3f7f52ef081d9 to your computer and use it in GitHub Desktop.
Save artikus11/dfe4e573204cae3d11e3f7f52ef081d9 to your computer and use it in GitHub Desktop.
Обрезка текста
/*
* Пример использования функции get_truncate()
*/
// Обрезка контента поста по буквам
$page = get_post( 28 );
echo get_truncate( apply_filters( 'the_content', $page->post_content ), 133 );
// Обрезка контента поста по словам
$page = get_post( 28 );
echo get_truncate( apply_filters( 'the_content', $page->post_content ), 33, false );
/**
* Обрека текста по симмволам или словам
*
* @param string $string_truncate обрезаемая строка
* @param int $length длина строки
* @param bool $letters по умолчанию по буквам
* @param string $ellipsis окончание строки, по умолчанию многоточие
*
* @return string
*
* @author unknown
* @refactor Artem Abramovich
* @verphp 7.0
*/
function get_truncate( string $string_truncate, $length = 40, $letters = true, $ellipsis = '…' ): string {
$string_truncate = preg_replace( '~\[/?.*?\](?!\()~', '', $string_truncate );
if ( false !== $letters ) {
if ( mb_strlen( $string_truncate ) > $length ) {
$string_truncate = sprintf(
'%1$s%2$s',
mb_substr( $string_truncate, 0, $length ),
$ellipsis
);
}
} else {
$words = explode( ' ', $string_truncate );
if ( count( $words ) > $length ) {
$string_truncate = sprintf(
'%1$s%2$s',
implode( ' ', array_slice( $words, 0, $length ) ),
$ellipsis
);
}
}
return $string_truncate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment