php karakter her üçüncü örneği patlayabilir

7 Cevap

Nasıl bir parçası olarak ;) (her üç noktalı virgül patlayabilir?

example data: $string = piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;

örnek çıktı olacaktır:

$ Çıkış [0] = piece1; piece2: piece3;

$ Çıkış [1] = piece4; piece5, piece6;

$ Çıkış [2] = piece7; piece8;

Teşekkürler!

7 Cevap

Ben Düzenli ifadeler ile kaygan bir şey yapabilirim eminim, ama neden sadece her semicolor patlayabilir ve daha sonra onları bir anda üç eklemeyin.

$tmp = explode(";", $string);
$i=0;
$j=0;

foreach($tmp as $piece) {
   if(! ($i++ %3)) $j++;   //increment every 3 
   $result[$j] .= $piece;
}

Esasen aynı explode diğerleri gibi çözüm ve yeniden katılmak ...

$tmp = explode(";", $string);

while ($tmp) {
    $output[] = implode(';', array_splice($tmp, 0, 3));
};

Aklıma en kolay çözüm:

$chunks = array_chunk(explode(';', $input), 3);
$output = array_map(create_function('$a', 'return implode(";",$a);'), $chunks);

Belki farklı bir açıdan yaklaşım. ) Tüm, sonra üçüzlerde geri birleştirmek (patlayabilir. Şöyle ...

$str = "1;2;3;4;5;6;7;8;9";
$boobies = explode(";", $array);
while (!empty($boobies))
{
  $foo = array();
  $foo[] = array_shift($boobies);
  $foo[] = array_shift($boobies);
  $foo[] = array_shift($boobies);
  $bar[] = implode(";", $foo) . ";";
}

print_r($bar);

Array ( [0] => 1;2;3; [1] => 4;5;6; [2] => 7;8;9; )

Başka bir regex yaklaşım.

<?php
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8';
preg_match_all('/([^;]+;?){1,3}/', $string, $m, PREG_SET_ORDER);
print_r($m);

Sonuçlar:

Array
(
    [0] => Array
        (
            [0] => piece1;piece2;piece3;
            [1] => piece3;
        )

    [1] => Array
        (
            [0] => piece4;piece5;piece6;
            [1] => piece6;
        )

    [2] => Array
        (
            [0] => piece7;piece8
            [1] => piece8
        )

)

Burada isteyen tüm çok iyi olduğunu söyleyemeyiz bir regex yaklaşım var.

$str='';
for ($i=1; $i<20; $i++) {
    $str .= "$i;";
}

$split = preg_split('/((?:[^;]*;){3})/', $str, -1,
                    PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

Çıktı:

Array
(
    [0] => 1;2;3;
    [1] => 4;5;6;
    [2] => 7;8;9;
    [3] => 10;11;12;
    [4] => 13;14;15;
    [5] => 16;17;18;
    [6] => 19;
)

Regex Bölünmüş

$test = ";2;3;4;5;6;7;8;9;10;;12;;14;15;16;17;18;19;20";
// match all groups that:
// (?<=^|;) follow the beginning of the string or a ;
// [^;]*  have zero or more non ; characters
// ;? maybe a semi-colon (so we catch a single group)
// [^;]*;? again (catch second item)
// [^;]* without the trailing ; (to not capture the final ;)
preg_match_all("/(?<=^|;)[^;]*;?[^;]*;?[^;]*/", $test, $matches);
var_dump($matches[0]);


array(7) {
  [0]=>
  string(4) ";2;3"
  [1]=>
  string(5) "4;5;6"
  [2]=>
  string(5) "7;8;9"
  [3]=>
  string(6) "10;;12"
  [4]=>
  string(6) ";14;15"
  [5]=>
  string(8) "16;17;18"
  [6]=>
  string(5) "19;20"
}