2010-11-15 19 views
0

下面的代碼可以將兩個變量從一個文件遷移到另一個文件中。如何使用PHP使用兩個標識符將一組文本從文件傳輸到文件?

<?php 
$file = 'somefile.txt'; 
// Open the file to get existing content 
$current = fopen($file,'a'); 
// Append a new person to the file 
$firstname .= "aiden\n"; 
$secondname .= "dawn\n"; 
$currentContent = file_get_contents($file); 
// Write the contents back to the file 
$fileFound = 'people.txt'; 
$newFile = fopen($fileFound,'a'); 
//if $current and $nextcurrent is found in the somefile.txt it will transfer the content to people.txt 
if (strpos($currentContent,$firstname) !== 0) 
{ 
if (strpos($currentContent,$secondname) !== 0) 
{ 
    fwrite($newFile, $currentContent."\n"); 
    } // endif 
}// endif 
?> 

接下來的問題是,我如何能夠將文本從標識符1遷移到標識符2? 我想我必須在這裏使用substrstrrpos字符串。 幫助請:)

回答

0

我很難理解問題,但看起來像試圖在文件中包含'aiden'和'dawn'之間的任何內容,並將結果寫入新文件。

給這一個

$firstIdentifier = 'aiden'; 
$secondIdentifier = 'dawn'; 
$currentContent = str_replace("\n", "", file_get_contents('sourcefile.txt')); 
$pattern = '/('.$firstIdentifier.')(.+?)('.$secondIdentifier.')/'; 

//get all text between the two identifiers, and include the identifiers in the match result 
preg_match_all($pattern, $currentContent , $matches); 

//stick them together with space delimiter 
$contentOfNewFile = implode(" ",$matches[0]); 

//save to a new file 
$newFile = fopen('destinationFile.txt','a'); 
fwrite($newFile, $contentOfNewFile); 
+0

的destination.txt不包含任何文字了一槍。 :( – woninana 2010-11-16 04:58:00

+0

它工作在我身邊。我的sourcefile.txt包含:「aidenhellodawn w245345 sdgdfty 34534rtsdfg sdgd345 aidenworlddawn」,destinationFile.txt在運行腳本後包含「aidenhellodawn aidenworlddawn」 – xar 2010-11-16 08:48:22

+0

我已經嘗試再次運行代碼,它這次工作。從上次運行這個以來,sourceFile.txt包含:aiden(換行符)一些文本在這裏(換行符)黎明 – woninana 2010-11-16 09:07:33

0
  1. 你不需要fopen當您使用file_get_contents
  2. 而不是使用一個分隔符,我建議你只序列化的變量

在文件1:

file_put_contents('somefile.txt',serialize(array($firstname,$lastname))); 

在文件2:

list($firstname,$lastname) = unserialize(file_get_contents('somefile.txt')) 
相關問題