note 111419 deleted from function.explode by salathe

From: Date: Mon, 21 Sep 2020 14:50:00 +0000
Subject: note 111419 deleted from function.explode by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215339@lists.php.net to get a copy of this message
Note Submitter: m.reesinck ---- I needed a multiexplode which didn't replace my delimiters for 1 other delimiter. Because I couldn't find one in the examples I made one. delimiter array: array('/RTRN/','/BUSP/','/BENM/','/ORDP/','/CSID/', '/MARF/','/EREF/', '/PREF/','/REMI/','/ID/','/PURP/', '/ULTB/','/ULTD/'); input string: /RTRN/MS03//BENM/NL50INGB00012345/BUSP/Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB///CSID/NL32ZZZ999999991234//MARF/EV45451//EREF/EV45451 REP170112T1106//REMI///EV45451REP170112T1106/ output: array( [/RTRN/] => MS03/ [/BENM/] => NL50INGB00012345 [/BUSP/] => Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB// [/CSID/] => NL32ZZZ999999991234/ [/MARF/] => EV45451/ [/EREF/] => EV45451REP170112T1106/ [/REMI/] => //EV45451REP170112T1106/ [/ORDP/] => [/PREF/] => [/ID/] => [/PURP/] => [/ULTB/] => [/ULTD/] => ) <?php function multiexplode($delimiters,$string) { $arrOccurence = array(); $arrEnd = array(); foreach($delimiters as $key => $value){ $position = strpos($string, $value); if($position > -1){ $arrOccurence[$value] = $position; } } if(count($arrOccurence) > 0){ asort($arrOccurence); $arrEnd = array_values($arrOccurence); array_shift($arrEnd); $i = 0; foreach($arrOccurence as $key => $start){ $pointer = $start+strlen($key); if($i == count($arrEnd)){ $arrOccurence[$key] = substr($string, $pointer); } else { $arrOccurence[$key] = substr($string, $pointer, $arrEnd[$i]-$pointer); } $i++; } } //next part can be left apart if not necessary. In that case key that don't appear in the inputstringwill not be returned foreach($delimiters as $key => $value){ if(!isset($arrOccurence[$value])){ $arrOccurence[$value] = ''; } } return $arrOccurence; } ?>

« previous php.notes (#215339) next »