user3136941
user3136941

Reputation: 91

Replace every seven comma with line break in php

I have comma separated data that repeat every seven data entries (a,b,c,d,e,f,g,a,b,c,d,e,f,g,a,b,c,d,e,f,g,a,b,c,d,e,f,g,a,b,c,d,e,f,g) I want to replace every seventh comma with line break to have data as shown below.

1. a,b,c,d,e,f,g
2. a,b,c,d,e,f,g
3. a,b,c,d,e,f,g
4. a,b,c,d,e,f,g
5. a,b,c,d,e,f,g

I have tried but I'm new with php. Here is what I've done:

$data = file_get_contents("Fundo.txt");

$total = explode(",", $data);
for ($i = 0; $i < count($total); $i++)
{
    $temp = explode(',', $total[$i]);
    $Id = $temp[0];

    echo $Id . "\n"; 
}

Upvotes: 2

Views: 85

Answers (2)

Dave Chen
Dave Chen

Reputation: 10975

Here's another method, and this one works if your data includes words instead of just letters.

<?php

$data = 'a,b,c,d,e,f,g,a,b,c,d,e,f,g,a,b,c,d,e,f,hello,world,universe,c,d,e,f,g,a,b,c,d,e,f,g';

$exploded = explode(',', $data);
$final = '';

for ($i = 0; $i < count($exploded); $i += 7)
    $final .= implode(',', array_slice($exploded, $i, 7)) . "\n";

echo $final;

Output:

a,b,c,d,e,f,g
a,b,c,d,e,f,g
a,b,c,d,e,f,hello
world,universe,c,d,e,f,g
a,b,c,d,e,f,g

Upvotes: 3

Droid
Droid

Reputation: 569

$data = file_get_contents("Fundo.txt");
echo preg_replace('!([a-g,]{13}),?!', "$1\n", $data);

[a-g] - symbols in string, you can replace by \w or .

{13} - means 13 chars

,? - removes ,

output

a,b,c,d,e,f,g
a,b,c,d,e,f,g
a,b,c,d,e,f,g
a,b,c,d,e,f,g
a,b,c,d,e,f,g

Upvotes: 3

Related Questions