如何通过多个定界符分解字符串并保留定界符?

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

我正在尝试使用多个定界符 (↑↑ , ↑ , ↓↓ , ↓) 分解字符串。

例如我有这个输入字符串:

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

我想将它转换成这样的数组(预期输出):

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

我最好的尝试打印了这个(当前输出):

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

这是我当前的代码:

<?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)));
    }

?>

我正在按照这种格式构建它,因为我要循环这些值并在 powerpoint 中打印它们,而那些分隔符(箭头)有不同的颜色

这应该适合你:

只需使用 preg_split() 并设置标志以保留分隔符。例如

<?php

    $string = "(2.8 , 3.1) → (↓↓2.4 , ↓3.0)";
    $arr =  preg_split("/(↑↑|↑|↓↓|↓)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
    print_r($arr);

?>

输出:

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