Jump to content

Write first character


Redapple

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

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.