Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. AbstractString.php

function AbstractString::truncate

File

vendor/symfony/string/AbstractString.php, line 613

Class

AbstractString
Represents a string of abstract characters.

Namespace

Symfony\Component\String

Code

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;
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal