note 100618 deleted from function.explode by danbrown
| From: | danbrown@php.net | Date: | Wed, 27 Oct 2010 13:45:02 +0000 |
| Subject: | note 100618 deleted from function.explode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173502@lists.php.net to get a copy of this message | ||
Note Submitter: ben at hydroprofessional dot com
----
An improved version of the multiExplode function, features:
- Ability to set keys ($k, $ks)
- Explodes even when one of the delimiters doesn't exist - keeps organisation ($has)
Feel free to optimise and update the code.
<?php
// Benjamin Fleming 2010
// www.hydroprofessional.com
function multiExplode($a, $s, $k=false, $ks="::") {
$r = explode($a[0], $s);
if($k) {
$nr = array();
$set = false;
for($i = 0; $i < count($r); $i++) {
$sp = strpos($r[$i], $ks);
if($sp !== false) {
$set = true;
$key = strstr($r[$i],$ks,true);
if($key != "") {
$nr[strstr($r[$i],$ks,true)] = substr(strstr($r[$i],$ks),2);
} else {
$nr[] = substr(strstr($r[$i],$ks),2);
}
} else {
$nr[] = $r[$i];
}
}
if($set) $r = $nr;
}
array_shift($a);
if(isset($a[0])) {
foreach($r as $key => $val) {
$has = false;
foreach($a as $val2) if(strpos($val, $val2) !== false) $has = true;
if($has || strpos($val, $ks) !== false) $r[$key] = multiExplode($a, $val, $k, $ks);
}
}
return $r;
}
$delimiters = array("||", "][", "}{");
$string = "Key 1::Lorem||Key 2::ipsum][dolor][Key 3::sit||amet,||Key 4::::Key
5::consectetur}{adipiscing][elit.";
echo '<pre>';
print_r(multiExplode($delimiters, $string, true));
echo '</pre>';
/*
Output:
Array
(
[Key 1] => Lorem
[Key 2] => Array
(
[0] => ipsum
[1] => dolor
[Key 3] => sit
)
[0] => amet,
[Key 4] => Array
(
[0] => Array
(
[Key 5] => consectetur
[0] => adipiscing
)
[1] => elit.
)
)
Notes:
- Keys wont be added if they are blank. Instead it just appends the data normally. This can be used
as an advantage, however. Note the usage of :::: (two key separaters) in my example.
*/
?>