note 43613 added to ref.array
| From: | reverseesacdaehasinhojatoohaydotmoc at rn2 dot php dot net | Date: | Mon, 28 Jun 2004 07:39:55 +0000 |
| Subject: | note 43613 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-71967@lists.php.net to get a copy of this message | ||
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
)
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43613
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43613&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43613&report=yes
Search -- http://master.php.net/manage/user-notes.php