php - How can I explode a string by multiple delimiters and also keep the delimiters? -


i'm trying explode string using multiple delimiters (↑↑ , ↑ , ↓↓ , ↓).

for example have intput string:

$string = "(2.8 , 3.1) → (↓↓2.4 , ↓3.0)"; 

i convert array (expected output):

array (     [0] => (2.8 , 3.1) → (     [1] => ↓↓     [2] => 2.4 ,      [3] => ↓     [4] => 3.0) ) 

my best attempt prints me (current output):

array (     [0] => (2.8 , 3.1) → (     [1] => ↓     [2] => ↓2.4 ,      [3] => ↓3.0) ) 

this current code:

<?php      function multiexplode ($delimiters,$string) {         return explode(             $delimiters[0],             strtr(                 $string,                 array_combine(                     array_slice($delimiters,1),                     array_fill(0,count($delimiters)-1,array_shift($delimiters))                 )             )         );     }      $delimiters = array('↑↑','↑','↓↓','↓');     $test = array('2up↑↑','1up↑','2down↓↓','1down↓');     $newdel = array('2up','1up','2down','1down');     $array = array();      $strings = array(         "(2.8 , 3.1) → (↓↓2.4 , ↓3.0)",         "(2.7 , 2.6) → (↑2.8 , ↑↑3.0)",         "(2.0 , 3.4) → (↑↑2.8 , ↓↓2.3)"     );      foreach($strings $string){         foreach($test $key => $reps){             $string = str_replace(                               $delimiters[$key],                 $reps,                 $string             );         }         //echo $string;         $array[] = array_values(array_filter(multiexplode($newdel,$string)));     }  ?> 

i'm building format, because i'm going loop values , print inside powerpoint , delimeters(arrows) have different colors

this should work you:

just use preg_split() , set flags keep delimiters. e.g.

<?php      $string = "(2.8 , 3.1) → (↓↓2.4 , ↓3.0)";     $arr =  preg_split("/(↑↑|↑|↓↓|↓)/", $string, -1, preg_split_delim_capture);     print_r($arr);  ?> 

output:

array (     [0] => (2.8 , 3.1) → (     [1] => ↓↓     [2] => 2.4 ,      [3] => ↓     [4] => 3.0) ) 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -