2010-11-12 105 views
0

此代碼允許創建新的.txt文件,如果該文件尚不存在,則會創建該文件。搜索文件並將搜索詞遷移到新文件

<?php 
$file = 'people.txt'; 
// Open the file to get existing content 
$current = file_get_contents($file); 
// Append a new person to the file 
$current .= "John Smith\n"; 
// Write the contents back to the file 
file_put_contents($file, $current); 
?> 

而這裏的代碼標識了每一行字符串到一個標記。

<?php 
$string = "This is\tan example\nstring"; 
/* Use tab and newline as tokenizing characters as well */ 
$tok = strtok($string, " \n\t"); 

while ($tok !== false) { 
    echo "Word=$tok<br />"; 
    $tok = strtok(" \n\t"); 
} 
?> 

的people.txt看起來像這樣

John Smith 
John Meyer 
John Chase 
John Smith //i want to transfer this set of string into a new file 

我失去的是什麼?

+2

你的問題是什麼? – 2010-11-12 14:04:21

+0

我想通過首先識別第一個和最後一個字符串,將一組字符串轉換爲不同的文件。 – woninana 2010-11-12 14:10:07

回答

0
$searchTerm = 'John Smith'; 
$file = 'people.txt'; 
$fileFound = 'peopleFound.txt'; 
$current = file_get_contents($file); 
if (strpos($searchTerm, $current) !== false) { 
    file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND); 
} 
+0

我明白了,謝謝:) – woninana 2010-11-14 12:15:32

+0

我想添加一些問題,如果約翰史密斯將被設置爲標識符,以便它可以傳輸*約翰史密斯*字符串之間的文本集呢? – woninana 2010-11-14 12:24:38

+0

「約翰史密斯」和什麼? – 2010-11-15 07:19:09

0
$fp=fopen('people.txt','a+'); 
fputs($fp,"John Smith\r\n"); 
fclose($fp); 

打開並附加文件,不要全部讀入並追加到後面並將其全部寫回。當文件超過一定的大小時,這將是真正的低效率。我不確定你是如何標記它的。在我看來,你可以做一個$names=file('people.txt');,並立即在陣列中...