Jump to content

[SOLVED] String Question (kind of lost)


kevinridge

Recommended Posts

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

 

Link to comment
https://forums.phpfreaks.com/topic/89457-solved-string-question-kind-of-lost/
Share on other sites

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.

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);
     }
   }
?>

<?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); 
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.