具有特定字符的动态爆炸

时间:2017-12-31 12:31:53

标签: php explode

我试图在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中做到这一点?

3 个答案:

答案 0 :(得分:1)

您应该注意到初始字符串中以下划线分隔的值的数量,例如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

答案 1 :(得分:1)

这样的事情应该有效,$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);

答案 2 :(得分:1)

爆炸很容易:

$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