读取文件直到达到char然后用PHP编写

Hi this is my problem i want to read from a file till i reach a specific character and then write a string in a new line before that specific character with php i know how to read by fopen i also know how to read line by line i dont know the last part(inserting my string in the line before that) Look at This example please: MYfile Contains:

Hello 
How are You 
blab la 
...
#$?!
other parts of my file...

so know i want it to when it reached $?! put my string in the line before that assume that my string is I did it!

Now MYfile Contains:

Hello 
How are You 
blab la 
...
#I did it!
#$?!
other parts of my file...

How should i do this?!? What i've done so far:

$handle = @fopen("Test2.txt", "r");
if ($handle) 
{
while (($buffer = fgets($handle, 4096)) !== false) 
{
    if($buffer == "#?") echo $buffer;
}
if (!feof($handle)) {
    echo "Error: unexpected fgets() fail
";
}
fclose($handle);
}

You simply need to search for the $?! when reading the text.

As you are reading line by line, check it in each line.

Personally, I would read the whole file at once (assuming it is not too big) and replace the string with the vlaue required.

$needle = '$?!'; // or whatever string you want to search for
$valueToInsert = "I did it!"; // Add 
 if you need a new line

$filecontents = file_get_contents("Test2.txt"); // Read the whole file into string
$output = str_replace($needle, $valueToInsert . $needle, $filecontents);

echo $output; // show the result

Not tested the above code - might require tweaking.

Since you know your marker, can you make use of fseek to rewind back a number of bytes (set whence to SEEK_CUR) and then use fwrite to insert the data?

Something like:

$handle = @fopen("Test2.txt", "r");
if ($handle) 
{
    while (($buffer = fgets($handle, 4096)) !== false) 
    {
        if($buffer == "#?") {
            fseek($handle, -2, SEEK_CUR); // move back to before the '#?'
            fwrite($handle, 'I did it!');
            break; // quit the loop
        }
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail
";
    }
    fclose($handle);
}

Disclaimer: I've not tried the above so you may need to play about to get it working exactly, but it would seem like a possible solution (though perhaps not the ideal one!)