Redapple Posted January 20, 2008 Share Posted January 20, 2008 Hello everybody, Is the follow issue possible to solve? I've got a text file where I took 2 lines out of the 94.568 lines: Did Kevin put that sheep in the hole?*A:Yes Is Bob is a freelancer with experience?*A:No It needs to become the follow: Q:Did Kevin put that sheep in the hole?* A:Yes Q:Is Bob is a freelancer with experience?* A:No I know it must use the follow PHP script: str_replace("\n", "\nQ:", file_get_contents("file.txt")); How could I get this done without editing line for line? That will take me months. Quote Link to comment https://forums.phpfreaks.com/topic/86945-write-first-character/ Share on other sites More sharing options...
chronister Posted January 20, 2008 Share Posted January 20, 2008 I would read the file in as an array by using the file() function. Then line by line you can access it and do something like the following <?php $file = file('myfile.txt'); foreach($file as $line) { $newlines = explode('*', $line); $question = 'Q:'.$newlines[0].'*'; $answer = $newlines[1]; echo $question.'<br>'.$answer.'<br>'; } ?> I created a txt file with the 2 lines you posted, then I ran the above code I created, and this is what I ended up with. Q:Did Kevin put that sheep in the hole?* A:Yes Q:Is Bob is a freelancer with experience?* A:No This creates the structure that you want, then you will just need to take the $question and $answer vars and do what you want with them. Hope this helps Nate Quote Link to comment https://forums.phpfreaks.com/topic/86945-write-first-character/#findComment-444516 Share on other sites More sharing options...
Barand Posted January 20, 2008 Share Posted January 20, 2008 alternatively, create a new re-formatted file <?php $fin = fopen ('file.txt', 'r'); $fout= fopen ('file1.txt', 'w'); while (!feof ($fin)) { $line = str_replace ('*', "*\n", fgets($fin, 1024)); if (trim($line) != '') { fwrite ($fout, 'Q:'.$line); } } fclose ($fin); fclose ($fout); echo "Finished"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/86945-write-first-character/#findComment-444535 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.