Created
July 20, 2013 14:08
-
-
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.
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 | |
// 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