Skip to content

Commit e3855a9

Browse files
committed
fix: Str.toNoEmptyArray split error on contains special chars
1 parent 78c63f7 commit e3855a9

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Str/Traits/StringConvertTrait.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use function mb_convert_variables;
2323
use function mb_detect_encoding;
2424
use function mb_strwidth;
25+
use function preg_quote;
2526
use function preg_split;
2627
use function str_contains;
2728
use function str_pad;
@@ -30,6 +31,7 @@
3031
use function strlen;
3132
use function strpos;
3233
use function trim;
34+
use function vdump;
3335
use const PREG_SPLIT_NO_EMPTY;
3436

3537
/**
@@ -235,7 +237,12 @@ public static function toNoEmptyArray(string $str, string $sep = ',', int $limit
235237
return [];
236238
}
237239

238-
$pattern = $sep === ' ' ? '/\s+/' : "/\s*$sep\s*/";
240+
if ($sep === ' ') {
241+
$pattern = '/\s+/';
242+
} else {
243+
$pattern = '/\s*' . preg_quote($sep, '/') . '\s*/';
244+
}
245+
239246
return preg_split($pattern, $str, $limit, PREG_SPLIT_NO_EMPTY);
240247
}
241248

test/Str/StringHelperTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,21 @@ public function testStrpos(): void
104104
self::assertFalse(Str::notContains('abc', 'b'));
105105
}
106106

107+
public function testToNoEmptyArray(): void
108+
{
109+
$tests = [
110+
['ab, cd', ',', ['ab', 'cd']],
111+
['ab / cd', '/', ['ab', 'cd']],
112+
['ab | cd', '|', ['ab', 'cd']],
113+
[' fieldName some desc', ' ', ['fieldName', 'some', 'desc']],
114+
[' ab 0 cd ', ' ', ['ab', '0', 'cd']],
115+
];
116+
117+
foreach ($tests as [$given, $sep, $want]) {
118+
$this->assertEquals($want, Str::toNoEmptyArray($given, $sep));
119+
}
120+
}
121+
107122
public function testToArray_no_limit(): void
108123
{
109124
$tests = [

0 commit comments

Comments
 (0)