2016-05-24 39 views
0

我的電話號碼的文本文件,如下圖所示:如何通過線從一個文本文件中提取串線到另一個文本文件

2348089219281 2348081231580 2347088911847 2347082645764 2348121718153 2348126315930 2348023646683。

我想提取的每個號碼,從它剝去+234並用0替換,則在修改的號碼前面添加以下文本"Names" . "\t"

然後我想插入一個新的文本文件(行由行)這個新的字符串.. 這是我得到的代碼的new_textFile我寫道:

名稱00urce ID#3

名稱00urce ID#3

這裏是我的代碼:

$this_crap_file = fopen($old_file_name, "r"); 
$total_number_lines_for_this_crap_file = count($this_crap_file); 
while(!feof($this_crap_file)) 
{ 
    $the_new_writing = fopen($new_file_name, "a"); 
    $the_string = substr_replace($this_crap_file, "0", 0, 4); 
    $new_string = "Names" . "\t" . 0 . $the_string . "\n"; 
    fwrite($the_new_writing, $new_string); 
} 
fclose($this_crap_file); 
+2

你似乎沒有從文件中讀取任何東西。使用'fgets'來讀取文件中的行。 – apokryfos

+0

您應該將打開新文件的fopen()行移至while循環之前。就像現在一樣,您在通過循環的每次迭代中打開新文件。 –

+0

一開始? http://www.phpliveregex.com/p/fNz click preg_replace – Andreas

回答

1

fopen和括號之間沒有空格嗎?對不起,我沒有看到該聲明的相關性。

假設您的輸入文件每行只有一個電話號碼,並且它們都以'+234'開頭,那麼您可以使用正則表達式來挑選出您想放入新文件的部分,如此:

$this_crap_file = fopen($old_file_name, "r"); 
$the_new_writing = fopen($new_file_name, "a"); 

while ($line = fgets($this_crap_file)) 
{ 
    preg_match('/\+234(\d+)/', $line, $matches); 
    $new_string = "Names\t" . $matches[1] . "\n"; 
    fwrite($the_new_writing, $new_string); 
} 

fclose($the_new_writing); 
fclose($this_crap_file); 
+0

這也解決了'$ new_file_name'應該打開一次而不是每次迭代以防止主動分配 - 資源釋放的問題。 – apokryfos

+0

@Brian Showalter: 是的,它的工作原理!謝謝。 我從來沒有處理過文件。現在我懂了。 我將閱讀正則表達式。 我想選擇您的最後一篇文章作爲答案,但我只看到評級按鈕。 – Wasiu

相關問題