具有特定特征的动态爆炸

Dynamic explosion with specific character

我正在尝试提取 php 中的字符串并将其转换为逗号分隔的字符串

这是我正在使用的一些示例字符串以及我需要的结果:

输入:

 G1_C2_S3_T5  or  G4_C5_S4_T7_I6_H3

结果必须是:

  G1,G1_C2,G1_C2_S3,G1_C2_S3_T5

  or

  G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3

逗号分隔的输入长度可以是动态的

这是否正确:

  $arr = explode("_", $string, 2);
  $first = $arr[0];

我如何在 php 中做到这一点?

您应该注意到初始字符串中下划线分隔值的数量,例如G4_C5_S4_T7_I6_H3 (6) 等于所需字符串中逗号分隔值的数量,例如G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3 (6)。所以我们将在我们的第一个循环中使用这个数字 $end = count($parts).

$str = "G4_C5_S4_T7_I6_H3";
$newstr = '';

$parts = explode('_', $str);
$comma = '';

for ($i = 0, $end = count($parts); $i < $end; $i++) {
    $newstr .= $comma;

    $underscore = '';
    // build underscore-separated value
    // index i is used to indicate up which value to stop at for each iteration
    for ($j = 0; $j <= $i; $j++) {
        $newstr .= $underscore . $parts[$j];
        // set underscore after the first iteration of the loop
        $underscore = '_';
    }
    // set comma after the first iteration of the loop
    $comma = ',';
}

echo $newstr; // G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3

像这样应该可以,$string 是您正在使用的字符串

//explode by underscore
$parts = explode('_', $string);

$c = [];
//do until nothing else to pop from array
while (!empty($parts)) {
    $c[] = implode('_', $parts);
   //will pop element from end of array
    array_pop($parts);
}
//reverse 
$c = array_reverse($c);
//glue it with comma
echo implode(',', $c);

爆炸容易:

$parts = explode('_', $string);

现在你得到一个 $parts 数组,如 [ 'G1', 'C2', 'S3', 'T5' ]

您想将其转换为数组,以便每个项目都是该项目及其之前的所有其他项目的串联:

$prev  = [ ];
array_walk(
    $parts,
    function(&$value) use (&$prev) {
        $prev[] = $value;
        $value  = implode('_', $prev);
    }
);

现在 $parts 包含元素:

print implode(', ', $parts);

产量

G1, G1_C2, G1_C2_S3, G1_C2_S3_T5