Skip to content

Commit bf383b3

Browse files
Fan2Shreknicolas-grekas
authored andcommitted
Mb trim functions
1 parent 697a1da commit bf383b3

File tree

8 files changed

+407
-0
lines changed

8 files changed

+407
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ Polyfills are provided for:
7070
- the `mb_ucfirst` and `mb_lcfirst` functions introduced in PHP 8.4;
7171
- the `array_find`, `array_find_key`, `array_any` and `array_all` functions introduced in PHP 8.4;
7272
- the `Deprecated` attribute introduced in PHP 8.4;
73+
- the `mb_trim`, `mb_ltrim` and `mb_rtrim` functions introduced in PHP 8.4;
7374

7475
It is strongly recommended to upgrade your PHP version and/or install the missing
7576
extensions whenever possible. This polyfill should be used only when there is no

src/Mbstring/Mbstring.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@
5050
* - mb_substr_count - Count the number of substring occurrences
5151
* - mb_ucfirst - Make a string's first character uppercase
5252
* - mb_lcfirst - Make a string's first character lowercase
53+
* - mb_trim - Strip whitespace (or other characters) from the beginning and end of a string
54+
* - mb_ltrim - Strip whitespace (or other characters) from the beginning of a string
55+
* - mb_rtrim - Strip whitespace (or other characters) from the end of a string
5356
*
5457
* Not implemented:
5558
* - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
@@ -76,6 +79,8 @@ final class Mbstring
7679
['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'],
7780
];
7881

82+
private const CHARACTERS = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}";
83+
7984
private static $encodingList = ['ASCII', 'UTF-8'];
8085
private static $language = 'neutral';
8186
private static $internalEncoding = 'UTF-8';
@@ -980,6 +985,59 @@ private static function getEncoding($encoding)
980985
return $encoding;
981986
}
982987

988+
public static function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string
989+
{
990+
return self::mb_internal_trim('^[%s]+|[%s]+$', $string, $characters, $encoding);
991+
}
992+
993+
public static function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string
994+
{
995+
return self::mb_internal_trim('^[%s]+', $string, $characters, $encoding);
996+
}
997+
998+
public static function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string
999+
{
1000+
return self::mb_internal_trim('[%s]+$', $string, $characters, $encoding);
1001+
}
1002+
1003+
private static function mb_internal_trim(string $regex, string $string, ?string $characters = null, ?string $encoding = null): string
1004+
{
1005+
if (null === $encoding) {
1006+
$encoding = mb_internal_encoding();
1007+
}
1008+
1009+
self::assertEncoding($encoding, debug_backtrace()[1]['function'].'(): Argument #3 ($encoding) must be a valid encoding, "%s" given.');
1010+
1011+
if ('' === $characters) {
1012+
return null === $encoding ? $string : mb_convert_encoding($string, $encoding);
1013+
}
1014+
1015+
if (null === $characters) {
1016+
$characters = self::CHARACTERS;
1017+
}
1018+
1019+
$regexCharacter = preg_quote($characters ?? '', '/');
1020+
$regex = sprintf($regex, $regexCharacter, $regexCharacter);
1021+
1022+
if ('ASCII' === mb_detect_encoding($characters) && 'ASCII' === mb_detect_encoding($string) && !empty(array_intersect(str_split(self::CHARACTERS), str_split($string)))) {
1023+
$options = 'g';
1024+
} else {
1025+
$options = '';
1026+
}
1027+
1028+
try {
1029+
$test = mb_ereg_replace($regex, "", $string, $options);
1030+
1031+
if (null === $test) {
1032+
throw new \Exception();
1033+
}
1034+
1035+
return $test;
1036+
} catch (\Exception $e) {
1037+
return preg_replace('/'.$regex.'/', "", $string);
1038+
}
1039+
}
1040+
9831041
private static function assertEncoding(string $encoding, string $errorFormat): void
9841042
{
9851043
try {

src/Mbstring/bootstrap.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,19 @@ function mb_ucfirst(string $string, ?string $encoding = null): string { return p
144144
function mb_lcfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); }
145145
}
146146

147+
if (!function_exists('mb_trim')) {
148+
function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_trim($string, $characters, $encoding); }
149+
}
150+
151+
if (!function_exists('mb_ltrim')) {
152+
function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_ltrim($string, $characters, $encoding); }
153+
}
154+
155+
if (!function_exists('mb_rtrim')) {
156+
function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_rtrim($string, $characters, $encoding); }
157+
}
158+
159+
147160
if (extension_loaded('mbstring')) {
148161
return;
149162
}

src/Mbstring/bootstrap80.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,18 @@ function mb_ucfirst($string, ?string $encoding = null): string { return p\Mbstri
140140
function mb_lcfirst($string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); }
141141
}
142142

143+
if (!function_exists('mb_trim')) {
144+
function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_trim($string, $characters, $encoding); }
145+
}
146+
147+
if (!function_exists('mb_ltrim')) {
148+
function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_ltrim($string, $characters, $encoding); }
149+
}
150+
151+
if (!function_exists('mb_rtrim')) {
152+
function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Mbstring::mb_rtrim($string, $characters, $encoding); }
153+
}
154+
143155
if (extension_loaded('mbstring')) {
144156
return;
145157
}

src/Php84/Php84.php

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@
1313

1414
/**
1515
* @author Ayesh Karunaratne <[email protected]>
16+
* @author Pierre Ambroise <[email protected]>
1617
*
1718
* @internal
1819
*/
1920
final class Php84
2021
{
22+
private const CHARACTERS = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}";
23+
2124
public static function mb_ucfirst(string $string, ?string $encoding = null): string
2225
{
2326
if (null === $encoding) {
@@ -107,4 +110,66 @@ public static function array_all(array $array, callable $callback): bool
107110

108111
return true;
109112
}
113+
114+
public static function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string
115+
{
116+
return self::mb_internal_trim('^[%s]+|[%s]+$', $string, $characters, $encoding);
117+
}
118+
119+
public static function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string
120+
{
121+
return self::mb_internal_trim('^[%s]+', $string, $characters, $encoding);
122+
}
123+
124+
public static function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string
125+
{
126+
return self::mb_internal_trim('[%s]+$', $string, $characters, $encoding);
127+
}
128+
129+
private static function mb_internal_trim(string $regex, string $string, ?string $characters = null, ?string $encoding = null): string
130+
{
131+
if (null === $encoding) {
132+
$encoding = mb_internal_encoding();
133+
}
134+
135+
try {
136+
$validEncoding = @mb_check_encoding('', $encoding);
137+
} catch (\ValueError $e) {
138+
throw new \ValueError(sprintf('%s(): Argument #3 ($encoding) must be a valid encoding, "%s" given.', debug_backtrace()[1]['function'], $encoding));
139+
}
140+
141+
// BC for PHP 7.3 and lower
142+
if (!$validEncoding) {
143+
throw new \ValueError(sprintf('%s(): Argument #3 ($encoding) must be a valid encoding, "%s" given.', debug_backtrace()[1]['function'], $encoding));
144+
}
145+
146+
if ('' === $characters) {
147+
return null === $encoding ? $string : mb_convert_encoding($string, $encoding);
148+
}
149+
150+
if (null === $characters) {
151+
$characters = self::CHARACTERS;
152+
}
153+
154+
$regexCharacter = preg_quote($characters ?? '', '/');
155+
$regex = sprintf($regex, $regexCharacter, $regexCharacter);
156+
157+
if ('ASCII' === mb_detect_encoding($characters) && 'ASCII' === mb_detect_encoding($string) && !empty(array_intersect(str_split(self::CHARACTERS), str_split($string)))) {
158+
$options = 'g';
159+
} else {
160+
$options = '';
161+
}
162+
163+
try {
164+
$test = mb_ereg_replace($regex, "", $string, $options);
165+
166+
if (null === $test) {
167+
throw new \Exception();
168+
}
169+
170+
return $test;
171+
} catch (\Exception $e) {
172+
return preg_replace(sprintf('/%s/', $regex), "", $string);
173+
}
174+
}
110175
}

src/Php84/bootstrap.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,15 @@ function array_any(array $array, callable $callback): bool { return p\Php84::arr
3838
if (!function_exists('array_all')) {
3939
function array_all(array $array, callable $callback): bool { return p\Php84::array_all($array, $callback); }
4040
}
41+
42+
if (!function_exists('mb_trim') && extension_loaded('mbstring')) {
43+
function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Php84::mb_trim($string, $characters, $encoding); }
44+
}
45+
46+
if (!function_exists('mb_ltrim') && extension_loaded('mbstring')) {
47+
function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Php84::mb_ltrim($string, $characters, $encoding); }
48+
}
49+
50+
if (!function_exists('mb_rtrim') && extension_loaded('mbstring')) {
51+
function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string { return p\Php84::mb_rtrim($string, $characters, $encoding); }
52+
}

tests/Mbstring/MbstringTest.php

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,4 +808,127 @@ public static function lcFirstDataProvider(): array
808808
['ß', 'ß'],
809809
];
810810
}
811+
812+
/**
813+
* @covers \Symfony\Polyfill\Php84\Php84::mb_trim
814+
*
815+
* @dataProvider mbTrimProvider
816+
*/
817+
public function testMbTrim(string $expected, string $string, ?string $characters = null, ?string $encoding = null): void
818+
{
819+
$this->assertSame($expected, mb_trim($string, $characters, $encoding));
820+
}
821+
822+
/**
823+
* @covers \Symfony\Polyfill\Php84\Php84::mb_ltrim
824+
*
825+
* @dataProvider mbLTrimProvider
826+
*/
827+
public function testMbLTrim(string $expected, string $string, ?string $characters = null, ?string $encoding = null): void
828+
{
829+
$this->assertSame($expected, mb_ltrim($string, $characters, $encoding));
830+
}
831+
832+
/**
833+
* @covers \Symfony\Polyfill\Php84\Php84::mb_rtrim
834+
*
835+
* @dataProvider mbRTrimProvider
836+
*/
837+
public function testMbRTrim(string $expected, string $string, ?string $characters = null, ?string $encoding = null): void
838+
{
839+
$this->assertSame($expected, mb_rtrim($string, $characters, $encoding));
840+
}
841+
842+
public function testMbTrimException(): void
843+
{
844+
$this->expectException(\ValueError::class);
845+
mb_trim("\u{180F}", "", "NULL");
846+
}
847+
848+
public function testMbTrimEncoding(): void
849+
{
850+
$this->assertSame('', mb_convert_encoding(mb_trim("\x81\x40\x82\xa0\x81\x40", "\x81\x40", "SJIS"), "UTF-8", "SJIS"));
851+
$this->assertSame('226f575b', bin2hex(mb_ltrim(mb_convert_encoding("\u{FFFE}漢字", "UTF-16LE", "UTF-8"), mb_convert_encoding("\u{FFFE}\u{FEFF}", "UTF-16LE", "UTF-8"), "UTF-16LE")));
852+
$this->assertSame('6f225b57', bin2hex(mb_ltrim(mb_convert_encoding("\u{FEFF}漢字", "UTF-16BE", "UTF-8"), mb_convert_encoding("\u{FFFE}\u{FEFF}", "UTF-16BE", "UTF-8"), "UTF-16BE")));
853+
}
854+
855+
public function testMbTrimCharactersEncoding(): void
856+
{
857+
$strUtf8 = "\u{3042}\u{3000}";
858+
859+
$this->assertSame(1, mb_strlen(mb_trim($strUtf8)));
860+
$this->assertSame(1, mb_strlen(mb_trim($strUtf8, null, 'UTF-8')));
861+
862+
$old = mb_internal_encoding();
863+
mb_internal_encoding('Shift_JIS');
864+
$strSjis = mb_convert_encoding($strUtf8, 'Shift_JIS', 'UTF-8');
865+
866+
$this->assertSame(1, mb_strlen(mb_trim($strSjis)));
867+
$this->assertSame(1, mb_strlen(mb_trim($strSjis, null, 'Shift_JIS')));
868+
mb_internal_encoding($old);
869+
}
870+
871+
public static function mbTrimProvider(): iterable
872+
{
873+
yield ['ABC', 'ABC'];
874+
yield ['ABC', "\0\t\nABC \0\t\n"];
875+
yield ["\0\t\nABC \0\t\n", "\0\t\nABC \0\t\n", ''];
876+
877+
yield ['', ''];
878+
879+
yield ["あいうえおあお", " あいうえおあお ", " ", "UTF-8"];
880+
yield ["foo BAR Spa", "foo BAR Spaß", "ß", "UTF-8"];
881+
yield ["oo BAR Spaß", "oo BAR Spaß", "f", "UTF-8"];
882+
883+
yield ["oo BAR Spa", "foo BAR Spaß", "ßf", "UTF-8"];
884+
yield ["oo BAR Spa", "foo BAR Spaß", "", "UTF-8"];
885+
yield ["いうおえお", " あいうおえお あ", "", "UTF-8"];
886+
yield ["いうおえお", " あいうおえお あ", "", "UTF-8"];
887+
yield [" あいうおえお ", " あいうおえお a", "あa", "UTF-8"];
888+
yield [" あいうおえお a", " あいうおえお a", "\xe3", "UTF-8"];
889+
890+
yield ["", str_repeat(" ", 129)];
891+
yield ["a", str_repeat(" ", 129) . "a"];
892+
893+
yield ["", " \f\n\r\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}"];
894+
895+
yield [' abcd ', ' abcd ', ''];
896+
897+
yield ['f', 'foo', 'oo'];
898+
899+
yield ["foo\n", "foo\n", 'o'];
900+
}
901+
902+
public static function mbLTrimProvider(): iterable
903+
{
904+
yield ['ABC', 'ABC'];
905+
yield ["ABC \0\t\n", "\0\t\nABC \0\t\n"];
906+
yield ["\0\t\nABC \0\t\n", "\0\t\nABC \0\t\n", ''];
907+
908+
yield ['', ''];
909+
910+
yield [' test ', ' test ', ''];
911+
912+
yield ['いああああ', 'あああああああああああああああああああああああああああああああああいああああ', ''];
913+
914+
yield ["漢字", "\u{FFFE}漢字", "\u{FFFE}\u{FEFF}"];
915+
yield [' abcd ', ' abcd ', ''];
916+
}
917+
918+
public static function mbRTrimProvider(): iterable
919+
{
920+
yield ['ABC', 'ABC'];
921+
yield ["ABC", "ABC \0\t\n"];
922+
yield ["\0\t\nABC \0\t\n", "\0\t\nABC \0\t\n", ''];
923+
924+
yield ['', ''];
925+
926+
yield [" a", str_repeat(" ", 129) . "a"];
927+
928+
yield ['あああああああああああああああああああああああああああああああああい', 'あああああああああああああああああああああああああああああああああいああああ', ''];
929+
930+
yield [' abcd ', ' abcd ', ''];
931+
932+
yield ["foo\n", "foo\n", 'o'];
933+
}
811934
}

0 commit comments

Comments
 (0)