Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/86945-write-first-character/
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/86945-write-first-character/#findComment-444516
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/86945-write-first-character/#findComment-444535
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.