Skip to content

Commit c66bf2e

Browse files
committed
fix: Improve readability excerpt()
1 parent b4cbd76 commit c66bf2e

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

system/Helpers/text_helper.php

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -712,38 +712,44 @@ function alternator(...$args): string
712712
function excerpt(string $text, ?string $phrase = null, int $radius = 100, string $ellipsis = '...'): string
713713
{
714714
if (isset($phrase)) {
715-
$phrasePos = mb_stripos($text, $phrase);
716-
$phraseLen = mb_strlen($phrase);
715+
$phrasePosition = mb_stripos($text, $phrase);
716+
$phraseLength = mb_strlen($phrase);
717717
} else {
718-
$phrasePos = $radius / 2;
719-
$phraseLen = 1;
718+
$phrasePosition = $radius / 2;
719+
$phraseLength = 1;
720720
}
721721

722-
$pre = explode(' ', mb_substr($text, 0, $phrasePos));
723-
$pos = explode(' ', mb_substr($text, $phrasePos + $phraseLen));
722+
$beforeWords = explode(' ', mb_substr($text, 0, $phrasePosition));
723+
$afterWords = explode(' ', mb_substr($text, $phrasePosition + $phraseLength));
724724

725-
$prev = ' ';
726-
$post = ' ';
725+
$firstPartOutput = ' ';
726+
$endPartOutput = ' ';
727727
$count = 0;
728728

729-
foreach (array_reverse($pre) as $e) {
730-
if ((mb_strlen($e) + $count + 1) < $radius) {
731-
$prev = ' ' . $e . $prev;
729+
foreach (array_reverse($beforeWords) as $beforeWord) {
730+
$beforeWordLength = mb_strlen($beforeWord);
731+
732+
if (($beforeWordLength + $count + 1) < $radius) {
733+
$firstPartOutput = ' ' . $beforeWord . $firstPartOutput;
732734
}
733-
$count = ++$count + mb_strlen($e);
735+
736+
$count = ++$count + $beforeWordLength;
734737
}
735738

736739
$count = 0;
737740

738-
foreach ($pos as $s) {
739-
if ((mb_strlen($s) + $count + 1) < $radius) {
740-
$post .= $s . ' ';
741+
foreach ($afterWords as $afterWord) {
742+
$afterWordLength = mb_strlen($afterWord);
743+
744+
if (($afterWordLength + $count + 1) < $radius) {
745+
$endPartOutput .= $afterWord . ' ';
741746
}
742-
$count = ++$count + mb_strlen($s);
747+
748+
$count = ++$count + $afterWordLength;
743749
}
744750

745751
$ellPre = $phrase !== null ? $ellipsis : '';
746752

747-
return str_replace(' ', ' ', $ellPre . $prev . $phrase . $post . $ellipsis);
753+
return str_replace(' ', ' ', $ellPre . $firstPartOutput . $phrase . $endPartOutput . $ellipsis);
748754
}
749755
}

0 commit comments

Comments
 (0)