Skip to content

Instantly share code, notes, and snippets.

@elusiveunit
Created November 20, 2013 19:52
Show Gist options
  • Save elusiveunit/7569878 to your computer and use it in GitHub Desktop.
Save elusiveunit/7569878 to your computer and use it in GitHub Desktop.
<?php
/**
* Create an array from a hyphenated, newline separated string.
*
* Converts a string like:
*
* Tacos
* Hamburger
* - With cheese
* -- Cheddar
* -- Gouda
* - With bacon
* Sandwich
* - With ham
* Hot dog
* Pizza
*
* To:
*
* array(
* 'Tacos' => 'Tacos',
* 'Hamburger' => array(
* 'With cheese' => array(
* 'Cheddar' => 'Cheddar',
* 'Gouda' => 'Gouda',
* ),
* 'With bacon' => 'With bacon'
* ),
* 'Sandwich' => array(
* 'With ham' => 'With ham'
* ),
* 'Hot dog' => 'Hot dog',
* 'Pizza' => 'Pizza'
* )
*
* In addition to hyphens, em- and en-dashes count as level indicators.
*
* @param string $string To process.
* @param int $level Current array level. Intended to be used recursively by
* the function, but can also be used to flatten the structure x levels.
* @return array
*/
function string_to_array( $string, $level = 0 ) {
$level++;
// Newline NOT followed by a number of dashes, depending on current level.
// This will items followed by sub items in the same string, until they
// are split recursively on the next level.
$newline_split_regex = "/\R+(?![\—\–\-]{{$level}})/";
$clean_dashes_regex = '/^[\—\–\-\s]+/';
$array = preg_split( $newline_split_regex, trim( $string ) );
$return = array();
foreach ( $array as $value ) :
$value = trim( $value );
// If there are newlines in the item, we have sub items
if ( preg_match( '/\R/', $value ) ) :
// Split on first newline to get the sub items parent...
$sub_items = preg_split( '/\R+/', $value, 2 );
$sub_key = preg_replace( $clean_dashes_regex, '', $sub_items[0] );
// ...and use as the key here, while the sub items go though another
// round of splitting
$return[$sub_key] = string_to_array( $sub_items[1], $level );
// If not, there are no more levels here, so clean and add the value
else :
$value = preg_replace( $clean_dashes_regex, '', $value );
$return[$value] = $value;
endif;
endforeach;
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment