如何从一个文本文件到另一个文本文件逐行提取字符串

时间:2016-05-24 13:23:19

标签: php

我有一个如下电话号码的文本文件:

  

+2348089219281 +2348081231580 +2347088911847 +2347082645764 +2348121718153 +2348126315930 +2348023646683。

我想提取每个号码,从中删除+234并替换为0,然后在修改后的号码前添加以下文字"Names" . "\t"

然后我想将这个新字符串插入一个新的文本文件中(逐行)。 这是我在new_textFile中使用代码I' ve写的:

  

名称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);

1 个答案:

答案 0 :(得分: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);