Last active
July 22, 2021 11:10
-
-
Save artikus11/dfe4e573204cae3d11e3f7f52ef081d9 to your computer and use it in GitHub Desktop.
Обрезка текста
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Пример использования функции 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 ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Обрека текста по симмволам или словам | |
* | |
* @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