2012-11-22 27 views
3

嗨,這是我的問題,我想從文件中讀取,直到我到達特定的字符,然後在用PHP的特定字符之前在新行中寫入一個字符串知道如何的fopen讀書,我也知道如何逐行讀取我不知道最後一部分線(插入我的字符串之前該行) 請看下面的例子請: MYFILE包含:閱讀文件直到達到一個字符然後在PHP中寫入

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); 
} 

回答

1

在閱讀文本時,您只需搜索$?!即可。

當你在逐行閱讀時,請在每一行中檢查它。個人而言,我會一次讀取整個文件(假設它不是太大),並將字符串替換爲所需的vlaue。

$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 

未測試上述代碼 - 可能需要調整。

+0

謝謝你,但我仍然有一個問題,你的代碼不理解輸入文件,當你回聲輸出沒有輸入(/ n)在它應該如何處理! –

+0

沒有它的作品只是沒有echo/n作爲輸出非常感謝你! –

0

既然你知道你的標誌,你可以利用fseek倒帶回來的字節數(設定何處來SEEK_CUR),然後使用fwrite插入數據?

喜歡的東西:

$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); 
} 

免責聲明:我沒有嘗試過上面的,所以你可能需要發揮一下得到它的工作了,但是那似乎是一個可能的解決方案(儘管可能不理想一個!)

相關問題