Reputation: 91
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
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;
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
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