0

I have this to split a file into smaller files with 200000 characters each.

$i = 1;
$fp = fopen("styles.css",'r');
while(! feof($fp)) {
    $contents = fread($fp,200000);
    file_put_contents('styles'.$i.'.css',$contents);
    $i++;
}

However, splitting a css file requires more than that. I'll need to have each of them in correct css format. For example:

Original css:

.red {
    color: red;
    font-weight: bold;
    font-size: 15px;
    background: black;
}

.blue {
    color: blue;
}

What might happen:

.red {
    color: red;
    font-weight: bold;
    font-size: 15px;
    background: black;
-------------------split--------------------
}

.blue {
    color: blue;
}

What I expect

.red {
    color: red;
    font-weight: bold;
    font-size: 15px;
    background: black;
}
-------------------split--------------------

.blue {
    color: blue;
}

Is there a way to have PHP split file by number of character, but always make sure that every file ends with "}"? So some file has more than 200000 characters, and some file has less than 200000 characters.

This is not a duplicated question since I want to split file and keep all the pieces, not just cutting a string.

mee
  • 35
  • 5
  • You have an answer in the dupe. Nice question, BTW. See [the answer](http://stackoverflow.com/a/4665347/462627) by Dave. – Praveen Kumar Purushothaman May 24 '16 at 10:10
  • The problem is harder than you realize - with media queries, you can have nested braces: `@media(..){.blue{color:blue;}}` There are probably other edge cases as well. Probably best to use a full on css parser like https://github.com/sabberworm/PHP-CSS-Parser – Steve May 24 '16 at 10:17
  • @Steve thank you, I never thought of this – mee May 24 '16 at 10:29

0 Answers0