Skip to content

Commit 830eba1

Browse files
committed
And string util method for count string w & w/o ansi escape sequences
1 parent 2112b77 commit 830eba1

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Util/StringUtil.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,9 @@ public static function stripAnsiEscapeSequence(string $str) : string
4343
{
4444
return (string) preg_replace('/\x1b[^m]*m/', '', $str);
4545
}
46+
47+
public static function length(string $str, bool $ignoreAnsiEscapeSequence = true) : string
48+
{
49+
return mb_strlen($ignoreAnsiEscapeSequence ? self::stripAnsiEscapeSequence($str) : $str);
50+
}
4651
}

test/Util/StringUtilTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,28 @@ public function testSplitItemBug() : void
9191
StringUtil::wordwrap($test, 11)
9292
);
9393
}
94+
95+
public function testLengthIgnoresAnsiEscapeSequences() : void
96+
{
97+
$result = StringUtil::length("\x1b[7mfoo\x1b[0m");
98+
$this->assertEquals(3, $result);
99+
100+
$result = StringUtil::length("foobar\x1b[00m\x1b[01;31m");
101+
$this->assertEquals(6, $result);
102+
103+
$result = StringUtil::length("foo\x1b[00mbar\x1b[01;31mbaz\x1b[00m!!!\x1b[01;31m");
104+
$this->assertEquals(12, $result);
105+
}
106+
107+
public function testLengthIncludingAnsiEscapeSequences() : void
108+
{
109+
$result = StringUtil::length("\x1b[7mfoo\x1b[0m", false);
110+
$this->assertEquals(11, $result);
111+
112+
$result = StringUtil::length("foobar\x1b[00m\x1b[01;31m", false);
113+
$this->assertEquals(19, $result);
114+
115+
$result = StringUtil::length("foo\x1b[00mbar\x1b[01;31mbaz\x1b[00m!!!\x1b[01;31m", false);
116+
$this->assertEquals(38, $result);
117+
}
94118
}

0 commit comments

Comments
 (0)