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

Breadcrumb

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

function Application::splitStringByWidth

1 call to Application::splitStringByWidth()
Application::doRenderThrowable in vendor/symfony/console/Application.php

File

vendor/symfony/console/Application.php, line 1261

Class

Application
An Application is the container for a collection of commands.

Namespace

Symfony\Component\Console

Code

private function splitStringByWidth(string $string, int $width) : array {
    // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
    // additionally, array_slice() is not enough as some character has doubled width.
    // we need a function to split string not by character count but by string width
    if (false === ($encoding = mb_detect_encoding($string, null, true))) {
        return str_split($string, $width);
    }
    $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
    $lines = [];
    $line = '';
    $offset = 0;
    while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) {
        $offset += \strlen($m[0]);
        foreach (preg_split('//u', $m[0]) as $char) {
            // test if $char could be appended to current line
            if (mb_strwidth($line . $char, 'utf8') <= $width) {
                $line .= $char;
                continue;
            }
            // if not, push current line to array and make new line
            $lines[] = str_pad($line, $width);
            $line = $char;
        }
    }
    $lines[] = \count($lines) ? str_pad($line, $width) : $line;
    mb_convert_variables($encoding, 'utf8', $lines);
    return $lines;
}

API Navigation

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