From 34890aff9000ae80655f01ac10e06681275183a4 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Mon, 27 Jul 2020 03:44:25 +0000 Subject: [PATCH] [FORMATTING] Add option to split a string to array by both a comma and a space --- src/Util/Formatting.php | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/Util/Formatting.php b/src/Util/Formatting.php index 1b320a49de..4dce3f6ae6 100644 --- a/src/Util/Formatting.php +++ b/src/Util/Formatting.php @@ -158,13 +158,14 @@ abstract class Formatting const SPLIT_BY_SPACE = ' '; const SPLIT_BY_COMMA = ', '; + const SPLIT_BY_BOTH = '/[, ]/'; /** * Convert scalars, objects implementing __toString or arrays to strings * * @param mixed $value */ - public static function toString($value, string $split_type = SPLIT_BY_COMMA): string + public static function toString($value, string $split_type = self::SPLIT_BY_COMMA): string { if (!is_array($value)) { return (string) $value; @@ -178,11 +179,21 @@ abstract class Formatting * * @param mixed $output */ - public static function toArray(string $input, &$output, string $split_type = SPLIT_BY_COMMA): bool + public static function toArray(string $input, &$output, string $split_type = self::SPLIT_BY_COMMA): bool { $matches = []; if (preg_match('/^ *\[?([^,]+(, ?[^,]+)*)\]? *$/', $input, $matches)) { - $output = str_replace([' \'', '\'', ' "', '"'], '', explode($split_type[0], $matches[1])); + switch ($split_type) { + case self::SPLIT_BY_BOTH: + $arr = preg_split($split_type, $matches[1], 0, PREG_SPLIT_NO_EMPTY); + break; + case self::SPLIT_BY_COMMA: + $arr = preg_split('/, ?/', $matches[1]); + break; + default: + $arr = explode($split_type[0], $matches[1]); + } + $output = str_replace([' \'', '\'', ' "', '"'], '', $arr); $output = F\map($output, F\ary('trim', 1)); return true; }