@@ -43,35 +43,40 @@ function word_limiter(string $str, int $limit = 100, string $endChar = '…'
4343 /**
4444 * Character Limiter
4545 *
46- * Limits the string based on the character count. Preserves complete words
46+ * Limits the string based on the character count. Preserves complete words
4747 * so the character count may not be exactly as specified.
4848 *
4949 * @param string $endChar the end character. Usually an ellipsis
5050 */
51- function character_limiter (string $ str , int $ n = 500 , string $ endChar = '… ' ): string
51+ function character_limiter (string $ string , int $ limit = 500 , string $ endChar = '… ' ): string
5252 {
53- if (mb_strlen ($ str ) < $ n ) {
54- return $ str ;
53+ if (mb_strlen ($ string ) < $ limit ) {
54+ return $ string ;
5555 }
5656
5757 // a bit complicated, but faster than preg_replace with \s+
58- $ str = preg_replace ('/ {2,}/ ' , ' ' , str_replace (["\r" , "\n" , "\t" , "\x0B" , "\x0C" ], ' ' , $ str ));
58+ $ string = preg_replace ('/ {2,}/ ' , ' ' , str_replace (["\r" , "\n" , "\t" , "\x0B" , "\x0C" ], ' ' , $ string ));
59+ $ stringLength = mb_strlen ($ string );
5960
60- if (mb_strlen ( $ str ) <= $ n ) {
61- return $ str ;
61+ if ($ stringLength <= $ limit ) {
62+ return $ string ;
6263 }
6364
64- $ out = '' ;
65+ $ output = '' ;
66+ $ outputLength = 0 ;
67+ $ words = explode (' ' , trim ($ string ));
6568
66- foreach (explode (' ' , trim ($ str )) as $ val ) {
67- $ out .= $ val . ' ' ;
68- if (mb_strlen ($ out ) >= $ n ) {
69- $ out = trim ($ out );
69+ foreach ($ words as $ word ) {
70+ $ output .= $ word . ' ' ;
71+ $ outputLength = mb_strlen ($ output );
72+
73+ if ($ outputLength >= $ limit ) {
74+ $ output = trim ($ output );
7075 break ;
7176 }
7277 }
7378
74- return (mb_strlen ( $ out ) === mb_strlen ( $ str )) ? $ out : $ out . $ endChar ;
79+ return ($ outputLength === $ stringLength ) ? $ output : $ output . $ endChar ;
7580 }
7681}
7782
@@ -721,9 +726,9 @@ function excerpt(string $text, ?string $phrase = null, int $radius = 100, string
721726 $ beforeWords = explode (' ' , mb_substr ($ text , 0 , $ phrasePosition ));
722727 $ afterWords = explode (' ' , mb_substr ($ text , $ phrasePosition + $ phraseLength ));
723728
724- $ firstPartOutput = ' ' ;
725- $ endPartOutput = ' ' ;
726- $ count = 0 ;
729+ $ firstPartOutput = ' ' ;
730+ $ endPartOutput = ' ' ;
731+ $ count = 0 ;
727732
728733 foreach (array_reverse ($ beforeWords ) as $ beforeWord ) {
729734 $ beforeWordLength = mb_strlen ($ beforeWord );
0 commit comments