mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-02 21:41:19 +08:00
Fixes #7488: Added StringHelper::explode to perform explode with trimming and skipping of empty elements
This commit is contained in:
committed by
Alexander Makarov
parent
624db0e678
commit
12fe0c7b85
@ -234,4 +234,35 @@ class BaseStringHelper
|
||||
return mb_strtolower(mb_substr($string, -$bytes, null, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explodes string into array, optionally trims values and skips empty ones
|
||||
*
|
||||
* @param string $string String to be exploded.
|
||||
* @param string $delimiter Delimiter. Default is ','.
|
||||
* @param mixed $trim Whether to trim each element. Can be:
|
||||
* - boolean - to trim normally;
|
||||
* - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
|
||||
* - callable - will be called for each value instead of trim. Takes the only argument - value.
|
||||
* @param boolean $skipEmpty Whether to skip empty strings between delimiters. Default is false.
|
||||
* @return array
|
||||
*/
|
||||
public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false) {
|
||||
$result = explode($delimiter, $string);
|
||||
if ($trim) {
|
||||
if ($trim === true) {
|
||||
$trim = 'trim';
|
||||
} elseif (!is_callable($trim)) {
|
||||
$trim = function($v) use ($trim) {
|
||||
return trim($v, $trim);
|
||||
};
|
||||
}
|
||||
$result = array_map($trim, $result);
|
||||
}
|
||||
if ($skipEmpty) {
|
||||
// Wrapped with array_values to make array keys sequential after empty values removing
|
||||
$result = array_values(array_filter($result));
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user