Created
May 21, 2015 10:09
-
-
Save sbrl/248bde72ff02e26065eb to your computer and use it in GitHub Desktop.
Probably (not) the world's most advanced string splitting function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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