3

I'm trying to explode a string using multiple delimiters (↑↑ , ↑ , ↓↓ , ↓).

For example I have this intput string:

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

I would like to convert it into an array like this (expected output):

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

My best attempt prints me this (current output):

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

This is my 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 as $string){
        foreach($test as $key => $reps){
            $string = str_replace(              
                $delimiters[$key],
                $reps,
                $string
            );
        }
        //echo $string;
        $array[] = array_values(array_filter(multiexplode($newDel,$string)));
    }

?>

I'm building it like that format, because I'm going to loop those values and print those inside a powerpoint and those delimeters(arrows) have different colors

Rizier123
  • 58,877
  • 16
  • 101
  • 156
roullie
  • 2,830
  • 16
  • 26

1 Answers1

8

This should work for you:

Just use preg_split() and set the flags to keep the 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)
)
Rizier123
  • 58,877
  • 16
  • 101
  • 156