Skip to content

Instantly share code, notes, and snippets.

@mohsin
Created April 13, 2015 22:25
Show Gist options
  • Save mohsin/e82fe096cf9b42f5a6ee to your computer and use it in GitHub Desktop.
Save mohsin/e82fe096cf9b42f5a6ee to your computer and use it in GitHub Desktop.
Sass version of PHP explode
//
// Returns list after splitting a string by a delimiter string.
// Similar to PHP's explode function
//
@function explode($string, $delimiter: "", $separator: "space")
@if type-of($string) != "string"
@warn "`explode` function expecting a string; #{type-of($string)} given."
@return null
@if type-of($delimiter) != "string"
@warn "`explode` function expecting a string; #{type-of($delimiter)} given."
@return null
$result: ()
$length: str-length($string)
@if not index("space" "comma", $separator)
$separator: "space"
@if str-length($delimiter) == 0
@for $i from 1 through $length
$result: append($result, str-slice($string, $i, $i))
@return $result
$running: true
$remaining: $string
@while $running
$index: str-index($remaining, $delimiter)
@if not $index
$running: false
@else
$slice: str-slice($remaining, 1, $index - 1)
$result: append($result, $slice, $separator)
$remaining: str-slice($remaining, $index + str-length($delimiter))
@return append($result, $remaining, $separator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment