Skip to content

Commit b919656

Browse files
committed
add an methods
1 parent 935b499 commit b919656

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Str/StringHelper.php

+24
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
use function preg_split;
4343
use function random_bytes;
4444
use function str_pad;
45+
use function str_repeat;
4546
use function str_replace;
4647
use function str_split;
4748
use function strip_tags;
@@ -61,6 +62,8 @@
6162
*/
6263
abstract class StringHelper
6364
{
65+
public static $defaultEncoding = 'UTF-8';
66+
6467
use StringCaseHelperTrait;
6568
use StringCheckHelperTrait;
6669
use StringLengthHelperTrait;
@@ -102,6 +105,27 @@ public static function padRight($str, $padLen, string $padStr = ' '): string
102105
return $padLen > 0 ? str_pad((string)$str, (int)$padLen, $padStr) : (string)$str;
103106
}
104107

108+
/**
109+
* @param string $str
110+
* @param int $padLen
111+
* @param string $padStr
112+
* @param int $padType
113+
*
114+
* @return string
115+
*/
116+
public static function padByWidth($str,$padLen, string $padStr = ' ', int $padType = STR_PAD_RIGHT): string
117+
{
118+
$stringWidth = mb_strwidth((string)$str, self::$defaultEncoding);
119+
if ($stringWidth >= $padLen) {
120+
return (string)$str;
121+
}
122+
123+
$repeatTimes = (int)$padLen - $stringWidth;
124+
$buildString = str_repeat($padStr, $repeatTimes);
125+
126+
return $padType === STR_PAD_RIGHT ? $str . $buildString : $buildString . $str;
127+
}
128+
105129
////////////////////////////////////////////////////////////
106130
/// Security
107131
////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)