Skip to content

Instantly share code, notes, and snippets.

@furkanmustafa
Created July 20, 2013 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furkanmustafa/6045169 to your computer and use it in GitHub Desktop.
Save furkanmustafa/6045169 to your computer and use it in GitHub Desktop.
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