Skip to content

[String] Method width return the length, not the width #47004

Closed
@TBoileau

Description

@TBoileau

Symfony version(s) affected

5.4

Description

When I try to get the width of a text, containing several lines, I do not get its width but the length of the text.

How to reproduce

$text = "<<<END
This is a
multiline text
END";
u($text)->width(); // Returns 23, not 14 like the documentation

Possible Solution

public function width(bool $ignoreAnsiDecoration = true): int
{
    $width = 0;
    $s = str_replace(["\x00", "\x05", "\x07"], '', $this->string);

    if (str_contains($s, "\r")) {
        $s = str_replace(["\r\n", "\r"], "\n", $s);
    }

    if (!$ignoreAnsiDecoration) {
        $s = preg_replace('/[\p{Cc}\x7F]++/u', '', $s);
    }

    foreach (explode("\n", $s) as $s) {
        if ($ignoreAnsiDecoration) {
            $s = preg_replace('/(?:\x1B(?:
                \[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E]
                | [P\]X^_] .*? \x1B\\\\
                | [\x41-\x7E]
            )|[\p{Cc}\x7F]++)/xu', '', $s);
        }

        $lineWidth = $this->wcswidth($s);

        if ($lineWidth > $width) {
            $width = $lineWidth;
        }
    }

    return $width;
}

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions