Skip to content

Commit c6be589

Browse files
committed
add string to array converter method in Str
1 parent 25b1d76 commit c6be589

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

src/Illuminate/Support/Str.php

+25
Original file line numberDiff line numberDiff line change
@@ -2065,6 +2065,31 @@ public static function freezeUlids(?Closure $callback = null)
20652065
return $ulid;
20662066
}
20672067

2068+
/**
2069+
* Converts a string to array using the first found separator from the provided list.
2070+
*
2071+
* @param string $string The input string to convert
2072+
* @param array $separators List of possible separators to check
2073+
*/
2074+
public static function toArray(string $string, array $separators = [',', '-', '|', ';', ':', '/', '\\']): array
2075+
{
2076+
// If string is empty, return empty array early
2077+
if ($string === '') {
2078+
return [];
2079+
}
2080+
2081+
$result = [$string];
2082+
foreach ($separators as $separator) {
2083+
if (str_contains($string, $separator)) {
2084+
$result = explode($separator, $string);
2085+
break; // Exit once we find the first separator
2086+
}
2087+
}
2088+
2089+
return $result;
2090+
}
2091+
2092+
20682093
/**
20692094
* Remove all strings from the casing caches.
20702095
*

tests/Support/SupportStrTest.php

+57
Original file line numberDiff line numberDiff line change
@@ -1814,6 +1814,63 @@ public function count(): int
18141814

18151815
$this->assertSame('UserGroups', Str::pluralPascal('UserGroup', $countable));
18161816
}
1817+
1818+
public function testToArrayWithCommaSeparator(): void
1819+
{
1820+
$this->assertEquals(
1821+
['1', '2', '3'],
1822+
Str::toArray('1,2,3')
1823+
);
1824+
}
1825+
1826+
public function testToArrayWithDashSeparator(): void
1827+
{
1828+
$this->assertEquals(
1829+
['10', '20', '30'],
1830+
Str::toArray('10-20-30')
1831+
);
1832+
}
1833+
1834+
public function testToArrayWithPipeSeparator(): void
1835+
{
1836+
$this->assertEquals(
1837+
['a', 'b', 'c'],
1838+
Str::toArray('a|b|c')
1839+
);
1840+
}
1841+
1842+
public function testToArrayWithSlashSeparator(): void
1843+
{
1844+
$this->assertEquals(
1845+
['apple', 'banana', 'cherry'],
1846+
Str::toArray('apple/banana/cherry')
1847+
);
1848+
}
1849+
1850+
public function testToArrayWithCustomSeparators(): void
1851+
{
1852+
$this->assertEquals(
1853+
['1', '2', '3'],
1854+
Str::toArray('1*2*3', ['*'])
1855+
);
1856+
}
1857+
1858+
public function testToArrayWithNoSeparatorReturnsSingleElementArray(): void
1859+
{
1860+
$this->assertEquals(
1861+
['single'],
1862+
Str::toArray('single')
1863+
);
1864+
}
1865+
1866+
public function testToArrayWithEmptyStringReturnsEmptyStringArray(): void
1867+
{
1868+
$this->assertEquals(
1869+
[''],
1870+
Str::toArray('')
1871+
);
1872+
}
1873+
18171874
}
18181875

18191876
class StringableObjectStub

0 commit comments

Comments
 (0)