@@ -44,35 +44,40 @@ function word_limiter(string $str, int $limit = 100, string $endChar = '…'
4444 /**
4545 * Character Limiter
4646 *
47- * Limits the string based on the character count. Preserves complete words
47+ * Limits the string based on the character count. Preserves complete words
4848 * so the character count may not be exactly as specified.
4949 *
5050 * @param string $endChar the end character. Usually an ellipsis
5151 */
52- function character_limiter (string $ str , int $ n = 500 , string $ endChar = '… ' ): string
52+ function character_limiter (string $ string , int $ limit = 500 , string $ endChar = '… ' ): string
5353 {
54- if (mb_strlen ($ str ) < $ n ) {
55- return $ str ;
54+ if (mb_strlen ($ string ) < $ limit ) {
55+ return $ string ;
5656 }
5757
5858 // a bit complicated, but faster than preg_replace with \s+
59- $ str = preg_replace ('/ {2,}/ ' , ' ' , str_replace (["\r" , "\n" , "\t" , "\x0B" , "\x0C" ], ' ' , $ str ));
59+ $ string = preg_replace ('/ {2,}/ ' , ' ' , str_replace (["\r" , "\n" , "\t" , "\x0B" , "\x0C" ], ' ' , $ string ));
60+ $ stringLength = mb_strlen ($ string );
6061
61- if (mb_strlen ( $ str ) <= $ n ) {
62- return $ str ;
62+ if ($ stringLength <= $ limit ) {
63+ return $ string ;
6364 }
6465
65- $ out = '' ;
66+ $ output = '' ;
67+ $ outputLength = 0 ;
68+ $ words = explode (' ' , trim ($ string ));
6669
67- foreach (explode (' ' , trim ($ str )) as $ val ) {
68- $ out .= $ val . ' ' ;
69- if (mb_strlen ($ out ) >= $ n ) {
70- $ out = trim ($ out );
70+ foreach ($ words as $ word ) {
71+ $ output .= $ word . ' ' ;
72+ $ outputLength = mb_strlen ($ output );
73+
74+ if ($ outputLength >= $ limit ) {
75+ $ output = trim ($ output );
7176 break ;
7277 }
7378 }
7479
75- return (mb_strlen ( $ out ) === mb_strlen ( $ str )) ? $ out : $ out . $ endChar ;
80+ return ($ outputLength === $ stringLength ) ? $ output : $ output . $ endChar ;
7681 }
7782}
7883
@@ -722,9 +727,9 @@ function excerpt(string $text, ?string $phrase = null, int $radius = 100, string
722727 $ beforeWords = explode (' ' , mb_substr ($ text , 0 , $ phrasePosition ));
723728 $ afterWords = explode (' ' , mb_substr ($ text , $ phrasePosition + $ phraseLength ));
724729
725- $ firstPartOutput = ' ' ;
726- $ endPartOutput = ' ' ;
727- $ count = 0 ;
730+ $ firstPartOutput = ' ' ;
731+ $ endPartOutput = ' ' ;
732+ $ count = 0 ;
728733
729734 foreach (array_reverse ($ beforeWords ) as $ beforeWord ) {
730735 $ beforeWordLength = mb_strlen ($ beforeWord );
0 commit comments