PHP 读取并连接多个远程文件

我使用此代码读取多个远程文件:


$filters = [ "https://example.com/file.txt", "https://example.com/file1.txt", "https://example.com/file3.txt" ]


function parseFilterLists( $filters )

  {

    foreach( $filters as $filter ){

      $file =  file_get_contents( $filter );

      $parsed = preg_replace( '/!.*/', '', $file );

      $parsed = preg_replace( '/\|\|([\w\d]+(?:\.[\w]+)+)(?:[\^\$=~].*)/', '*://*.$1/*', $parsed ); 

    }

    $output = array_filter( explode( "\n", $parsed ), function($url){

      return preg_match('/^\*:\/\/\*\.[\w\d-]+\.[\w]+\/\*$/', $url);

    });

    return array_values(array_unique($output));

  }

我注意到输出内容被截断,就像只处理一个文件一样,但我需要的是连接三个文件来操作它们。我怎样才能实现这个目标?


达令说
浏览 126回答 2
2回答

喵喔喔

$parsed 的范围仅限于 foreach 循环,因此 $output 仅包含循环最后一次迭代的结果。您应该在循环之前定义 $output,并将每次迭代的结果附加到其中。<?php$filters = ["https://example.com/file.txt", "https://example.com/file1.txt", "https://example.com/file3.txt"];function parseFilterLists($filters){&nbsp; &nbsp; // Define a buffer for the output&nbsp; &nbsp; $output = [];&nbsp; &nbsp; foreach ($filters as $filter)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $file&nbsp; &nbsp;= file_get_contents($filter);&nbsp; &nbsp; &nbsp; &nbsp; $parsed = preg_replace('/!.*/', '', $file);&nbsp; &nbsp; &nbsp; &nbsp; $parsed = preg_replace('/\|\|([\w\d]+(?:\.[\w]+)+)(?:[\^\$=~].*)/', '*://*.$1/*', $parsed);&nbsp; &nbsp; &nbsp; &nbsp; // Get the output for the file we're working on in this iteration&nbsp; &nbsp; &nbsp; &nbsp; $currOutput = array_filter(explode("\n", $parsed), function ($url) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return preg_match('/^\*:\/\/\*\.[\w\d-]+\.[\w]+\/\*$/', $url);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; // Append the output from the current file to the output buffer&nbsp; &nbsp; &nbsp; &nbsp; $output = array_merge($output, $currOutput);&nbsp; &nbsp; }&nbsp; &nbsp; // Return the unique results&nbsp; &nbsp; return array_unique($output);}

慕码人8056858

我想这会如你所愿$filters = [&nbsp;&nbsp; "https://example.com/file.txt", "https://example.com/file1.txt", "https://example.com/file3.txt"];function parseFilterLists( $filters )&nbsp; {&nbsp; &nbsp; $files = [];&nbsp; &nbsp; foreach( $filters as $filter ){&nbsp; &nbsp; &nbsp; $files[] = file_get_contents( $filter );&nbsp; &nbsp; }&nbsp; &nbsp; $parsed = preg_replace( '/!.*/', '', implode("\n", $files));&nbsp; &nbsp; $parsed = preg_replace( '/\|\|([\w\d]+(?:\.[\w]+)+)(?:[\^\$=~].*)/', '*://*.$1/*', $parsed);&nbsp;&nbsp; &nbsp; $output = array_filter( explode( "\n", $parsed ), function($url){&nbsp; &nbsp; &nbsp; return preg_match('/^\*:\/\/\*\.[\w\d-]+\.[\w]+\/\*$/', $url);&nbsp; &nbsp; });&nbsp; &nbsp; return array_values(array_unique($output));&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP