function AbstractString::truncate
File
-
vendor/
symfony/ string/ AbstractString.php, line 613
Class
- AbstractString
- Represents a string of abstract characters.
Namespace
Symfony\Component\StringCode
public function truncate(int $length, string $ellipsis = '', bool|TruncateMode $cut = TruncateMode::Char) : static {
$stringLength = $this->length();
if ($stringLength <= $length) {
return clone $this;
}
$ellipsisLength = '' !== $ellipsis ? (new static($ellipsis))->length() : 0;
if ($length < $ellipsisLength) {
$ellipsisLength = 0;
}
$desiredLength = $length;
if (TruncateMode::WordAfter === $cut || !$cut) {
if (null === ($length = $this->indexOf([
' ',
"\r",
"\n",
"\t",
], ($length ?: 1) - 1))) {
return clone $this;
}
$length += $ellipsisLength;
}
elseif (TruncateMode::WordBefore === $cut && null !== $this->indexOf([
' ',
"\r",
"\n",
"\t",
], ($length ?: 1) - 1)) {
$length += $ellipsisLength;
}
$str = $this->slice(0, $length - $ellipsisLength);
if (TruncateMode::WordBefore === $cut) {
if (0 === $ellipsisLength && $desiredLength === $this->indexOf([
' ',
"\r",
"\n",
"\t",
], $length)) {
return $str;
}
$str = $str->beforeLast([
' ',
"\r",
"\n",
"\t",
]);
}
return $ellipsisLength ? $str->trimEnd()
->append($ellipsis) : $str;
}