3

嗨,这是我的问题,我想从文件中读取,直到我到达特定字符,然后在新行中用 php 在该特定字符之前写入一个字符串我知道如何通过 fopen 读取我也知道如何逐行读取我不知道最后一部分(在那之前的行中插入我的字符串)请看这个例子: MYfile 包含:

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

所以知道当它达到$时我想要它?!把我的字符串放在前面的那一行假设我的字符串是我做的!

现在 MYfile 包含:

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

我该怎么做?!?到目前为止我所做的:

$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\n";
}
fclose($handle);
}
4

2 回答 2

1

您只需要$?!在阅读文本时搜索。

当您逐行阅读时,请检查每一行。

就个人而言,我会一次读取整个文件(假设它不是太大)并将字符串替换为所需的值。

$needle = '$?!'; // or whatever string you want to search for
$valueToInsert = "I did it!"; // Add \r\n 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

未测试上述代码 - 可能需要调整。

于 2012-11-22T17:28:19.930 回答
0

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\n";
    }
    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!)

于 2012-11-22T17:22:16.627 回答