note 100618 added to function.explode

From: Date: Wed, 27 Oct 2010 04:41:01 +0000
Subject: note 100618 added to function.explode
Groups: php.notes 
Request: Send a blank email to php-notes+get-173493@lists.php.net to get a copy of this message
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. */ ?> ---- Server IP: 117.104.162.229 Probable Submitter: 115.64.165.37 (proxied: 115.64.165.37) ---- Manual Page -- http://www.php.net/manual/en/function.explode.php Edit -- https://master.php.net/note/edit/100618 Del: integrated -- https://master.php.net/note/delete/100618/integrated Del: useless -- https://master.php.net/note/delete/100618/useless Del: bad code -- https://master.php.net/note/delete/100618/bad+code Del: spam -- https://master.php.net/note/delete/100618/spam Del: non-english -- https://master.php.net/note/delete/100618/non-english Del: in docs -- https://master.php.net/note/delete/100618/in+docs Del: other reasons-- https://master.php.net/note/delete/100618 Reject -- https://master.php.net/note/reject/100618 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173493) next »