kevinridge Posted February 5, 2008 Share Posted February 5, 2008 Hello, I have confusing string question. I have a string like this (example): {FILE: hello} hello contents {FILE: hello2} hello2 contents What im trying to do is when the code reads {FILE: *} <- it makes that file. Than it puts all the contents in the file until it finds another {FILE: *} or the end of the string. I am sort of lost in the right direction to do this. Any sort of help would be great! Kev Quote Link to comment Share on other sites More sharing options...
Barand Posted February 5, 2008 Share Posted February 5, 2008 As your string seems to contain newline chars, explode() the string into separate lines using the newline chars. Then loop through the array. if line contains FILE: x close previous file (unless it's the first) open new file else write current line to the open file end if close file. Quote Link to comment Share on other sites More sharing options...
kevinridge Posted February 5, 2008 Author Share Posted February 5, 2008 Thanks for the reply but i am sort of confused how to check if it contains FILE: x and how to get the value of x out of that to use to make the file. Thanks again Kev Quote Link to comment Share on other sites More sharing options...
Caesar Posted February 5, 2008 Share Posted February 5, 2008 The following would work I suppose... <?php $files = explode("\n",$str); $i = 0; foreach($files as $line) { if(preg_match('/\{FILE: [aA-zZ]+\}/',$line)) { preg_match('/\{FILE: ([aA-zZ]+)\}/',$line,$f); $file[$i][file] = $f[1].".html"; } else { $file[$i][contents] = $line; $i++; } } foreach ($file as $c) { if($c[file] != "") { $handle = fopen($c[file],"w"); fwrite($handle,$c[contents]); fclose($handle); } } ?> Quote Link to comment Share on other sites More sharing options...
Barand Posted February 5, 2008 Share Posted February 5, 2008 <?php $str = '{FILE: hello.txt} hello contents {FILE: hello2.txt} hello2 contents'; $lines = explode ("\n", $str); $notFirst = 0; foreach ($lines as $line) { if (($p = strpos($line, 'FILE:') !== false)) { $filename = trim(substr($line, $p+5), ' )'); if ($notFirst) fclose ($fp); $fp = fopen ($filename, 'w'); $notFirst = 1; } else { fwrite ($fp, $line); } } fclose ($fp); ?> Quote Link to comment Share on other sites More sharing options...
kevinridge Posted February 5, 2008 Author Share Posted February 5, 2008 Wow. Works great Thanks! Kev Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.