doujiaoben28596 2016-05-24 13:23
浏览 38
已采纳

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

I have a text file of phone numbers like below:

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

I want to extract each number, strip +234 from it and replace with 0 , then add the following text "Names" . "\t" in front of the modified number.

Then I want to insert this new string in a new text file (line-by-line).. This is what I get in the new_textFile with the code I've wrote:

Names 00urce id #3

Names 00urce id #3

Here's my code:

$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 . "
";
  fwrite($the_new_writing, $new_string);
}
fclose($this_crap_file);
  • 写回答

1条回答 默认 最新

  • dpf71390 2016-05-24 17:38
    关注

    No space between fopen and the parenthesis? Sorry, I don't see the relevance of that statement.

    Assuming your input file only has one phone number per line, and that they all start with '+234', you could use a regular expression to pick out just the part you want to put in the new file, like this:

    $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] . "
    ";
      fwrite($the_new_writing, $new_string);
    }
    
    fclose($the_new_writing);
    fclose($this_crap_file);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答