Skip to content

Commit c757be6

Browse files
committed
add new method
1 parent 0bfbb69 commit c757be6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/StringHelper.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,4 +580,54 @@ public static function replaceStringInFile(string $filename, string $searchStrin
580580

581581
return $response;
582582
}
583+
584+
/**
585+
* Trims a string to a specified length, preserving the integrity of the last word.
586+
*
587+
* Обрезаем строку до заданной длины с учетом целостности последнего слова.
588+
*
589+
* This function will trim the input string to a maximum specified length without
590+
* cutting off the last word. If the next word would exceed the length limit,
591+
* the string is trimmed up to the previous word. If no spaces are found within
592+
* the limit, or if the first word exceeds the limit, an empty string is returned.
593+
*
594+
* @param string|null $sString The input string to be trimmed.
595+
* @param int $maxLength The maximum allowed length of the output string.
596+
* @param string $sDefault Default value.
597+
*
598+
* @return string The trimmed string with preserved last word integrity up to maxLength.
599+
*/
600+
public static function trimStringToLastWord(?string $sString = '', int $maxLength = 0, string $sDefault = ''): string
601+
{
602+
if ('' === $sString || null === $sString || 0 == $maxLength) {
603+
return $sDefault;
604+
}
605+
606+
$sString = \trim($sString);
607+
608+
// Return the original string if it is within maxLength.
609+
if (static::mb_strlen($sString) <= $maxLength) {
610+
return $sString;
611+
}
612+
613+
// Trim the string to maxLength first to see if we're cutting through a word.
614+
$trimmedString = static::mb_substr($sString, 0, $maxLength);
615+
616+
// Check if we are on a space or just passed one; if so, we can return early.
617+
if ($sString[$maxLength] == ' ' || $sString[$maxLength-1] == ' ') {
618+
return \rtrim($trimmedString);
619+
}
620+
621+
// Find the last space in our trimmed string to avoid cutting off a word.
622+
$lastSpacePosition = \strrpos($trimmedString, ' ');
623+
624+
// If there's no space at all, return an empty string as we cannot preserve any word.
625+
if ($lastSpacePosition === false) {
626+
return $sDefault;
627+
}
628+
629+
// Return substring up to the last found space position.
630+
return static::mb_substr($trimmedString, 0, $lastSpacePosition);
631+
}
632+
583633
}

0 commit comments

Comments
 (0)