Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Replacement for php's built-in explode function, doesn't break quotes, etc.
<?php
// a replacement for php's built-in explode function, doesn't break quotes, etc.
function nonBreakingExplode($delimiter, $string, $nobreakChars = array('"', '\'', '()', '[]')) {
$pos = 0;
$len = strlen($string);
$delimiterLen = strlen($delimiter);
$lastCut = 0;
$nest = array();
$lastNest = null;
$parts = array();
while ($pos <= $len - $delimiterLen) {
$char = substr($string, $pos, 1);
$delimTest = substr($string, $pos, $delimiterLen);
$width = $pos - $lastCut;
if ($lastNest == null && $delimTest == $delimiter) {
// CUT
if ($width==0) {
$parts[] = '';
} else {
$parts[] = substr($string, $lastCut, $width );
}
$lastCut = $pos + $delimiterLen;
$pos+=$delimiterLen; continue;
}
if (count($nest)>0) {
if ($char==substr($lastNest, -1, 1)) {
array_pop($nest);
$lastNest = count($nest) > 0 ? $nest[count($nest) - 1] : null;
$pos++; continue;
}
}
foreach ($nobreakChars as $charset) {
if ($char==substr($charset, 0, 1)) {
$nest[] = $charset;
$lastNest = $charset;
$pos++; continue 2;
}
}
$pos++;
}
if ($width==0) {
$parts[] = '';
} else {
$parts[] = substr($string, $lastCut);
}
return $parts;
}
/* Test Code */
$testText = "naber, abi, 'iyimisin, bugunlerde', bence (okada[r, )d,]a iyi) degilsin";
$start = microtime(true);
print_r(explode(',', $testText));
$took['explode'] = round((microtime(true) - $start) * 1000000) . ' nanoseconds';
$start = microtime(true);
print_r(nonBreakingExplode(',', $testText));
$took['nonBreakingExplode'] = round((microtime(true) - $start) * 1000000) . ' nanoseconds';
print_r($took);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment