Skip to content

Instantly share code, notes, and snippets.

@sbrl sbrl/explode_adv.php
Created May 21, 2015

Embed
What would you like to do?
Probably (not) the world's most advanced string splitting function.
<?php
/*******************************
* An advanced string splitting function written in PHP.
* Blog Post: https://starbeamrainbowlabs.com/blog/article.php?article=posts%2F077-PHP-String-Splittting.html
* Written by Starbeamrainbowlabs.
* Website: https://starbeamrainbowlabs.com
* Twitter: @SBRLabs
*/
function explode_adv($openers, $closers, $togglers, $delimiters, $str)
{
$chars = str_split($str);
$parts = [];
$nextpart = "";
$toggle_states = array_fill_keys($togglers, false); // true = now inside, false = now outside
$depth = 0;
foreach($chars as $char)
{
if(in_array($char, $openers))
$depth++;
elseif(in_array($char, $closers))
$depth--;
elseif(in_array($char, $togglers))
{
if($toggle_states[$char])
$depth--; // we are inside a toggle block, leave it and decrease the depth
else
// we are outside a toggle block, enter it and increase the depth
$depth++;
// invert the toggle block state
$toggle_states[$char] = !$toggle_states[$char];
}
else
$nextpart .= $char;
if($depth < 0) $depth = 0;
if(in_array($char, $delimiters) &&
$depth == 0 &&
!in_array($char, $closers))
{
$parts[] = substr($nextpart, 0, -1);
$nextpart = "";
}
}
if(strlen($nextpart) > 0)
$parts[] = $nextpart;
return $parts;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.