note 43613 deleted from ref.array by aidan
| From: | aidan@php.net | Date: | Sun, 09 Oct 2005 09:14:49 +0000 |
| Subject: | note 43613 deleted from ref.array by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-96737@lists.php.net to get a copy of this message | ||
Note Submitter: reverse esacdaehasinhoj at oohay dot moc
----
I've included a neat function I had to hack out, to handle exploding on multiple strings as
tokens without losing which token created the break. There's lots of room for improvement;
this function has bad behavior when tokens overlap, for instance, and doesn't provide any way
to discover what tokens occurred in what order (though, token order for a given delimiter is
preserved.) Should there be a piece of string before any delimiters, or should there be no
delimiter, the remainder will be stored in the result's index for null string.
Case sensitivity control is dependant on stripos(), which is only available in PHP5 CVS. PHP<5
may only use this function case sensitively unless a replacement is provided.
<?php
// function has incorrect results when delimiters overlap
function mexplode_dangerous($delimiters, $data, $casesensitive = true) {
$points = array();
foreach ($delimiters as $delim) {
$nextpoint = 0;
if ($casesensitive) {
while (!( ($point = strpos($data, $delim, $nextpoint)) === false )) {
$points[$point] = $delim;
$nextpoint = $point + strlen($delim);
}
} else {
while (!( ($point = stripos($data, $delim, $nextpoint)) === false )) {
$points[$point] = $delim;
$nextpoint = $point + strlen($delim);
}
}
}
if (count($points) == 0) {
return array('' => $data);
} else {
$start=strlen($data);
reset($points);
krsort($points);
while ($point = current($points)) {
$offset = key($points) + strlen($point);
$result[$point][] = substr($data, $offset, $start-$offset);
$start=key($points);
next($points);
}
reset($result);
while($row = current($result)) {
$output[key($result)] = array_reverse($row);
next($result);
}
$output['']=substr($data,0,$start);
return $output;
}
}
// Usage is fairly straightforward.
print_r(mexplode_dangerous(array('@','=','::','|'),
'hello@at1=eq1::colon1|pipe1|pipe2|pipe3::colon2::colon3=eq2@at2'));
?>
This should return:
Array
(
[@] => Array
(
[0] => at1
[1] => at2
)
[=] => Array
(
[0] => eq1
[1] => eq2
)
[::] => Array
(
[0] => colon1
[1] => colon2
[2] => colon3
)
[|] => Array
(
[0] => pipe1
[1] => pipe2
[2] => pipe3
)
[] => hello
)