forked from php-school/cli-menu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringUtil.php
More file actions
52 lines (47 loc) · 1.58 KB
/
Copy pathStringUtil.php
File metadata and controls
52 lines (47 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
declare(strict_types=1);
namespace PhpSchool\CliMenu\Util;
/**
* @author Michael Woodward <[email protected]>
*/
class StringUtil
{
/**
* Minimal multi-byte wordwrap implementation
* which also takes break length into consideration
*/
public static function wordwrap(string $string, int $width, string $break = "\n") : string
{
return implode(
$break,
array_map(function (string $line) use ($width, $break) {
$line = rtrim($line);
if (mb_strwidth($line) <= $width) {
return $line;
}
$words = explode(' ', $line);
$line = '';
$actual = '';
foreach ($words as $word) {
if (mb_strwidth($actual . $word) <= $width) {
$actual .= $word . ' ';
} else {
if ($actual !== '') {
$line .= rtrim($actual) . $break;
}
$actual = $word . ' ';
}
}
return $line . trim($actual);
}, explode("\n", $string))
);
}
public static function stripAnsiEscapeSequence(string $str) : string
{
return (string) preg_replace('/\x1b[^m]*m/', '', $str);
}
public static function length(string $str, bool $ignoreAnsiEscapeSequence = true) : int
{
return mb_strwidth($ignoreAnsiEscapeSequence ? self::stripAnsiEscapeSequence($str) : $str);
}
}