【问题标题】:Split one file and make them into two拆分一个文件并将它们分成两个
【发布时间】:2016-08-30 01:11:38
【问题描述】:
//expression to be found in file name
$find = '.5010.';

//directory name
//we will store renamed files here
$dirname = '5010';
if(!is_dir($dirname))
    mkdir($dirname, 0777);

//read all files from a directory
//skip directories
$directory_with_files = './';
$dh  = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
    if(in_array($filename, array('.', '..')) || is_dir($filename))
        continue;

    $files[] = $filename;
}

//iterate collected files
foreach($files as $file)
{
    //check if file name is matching $find
    if(stripos($file, $find) !== false)
    {

        //open file
        $handle = fopen($file, "r");
        if ($handle)
        {
            //read file, line by line
            while (($line = fgets($handle)) !== false)
            {

                //find REF line
                $refid = 'REF*2U*'; 
                if(stripos($line, $refid) !== false) 
                    { 
                    //glue refernce numbers 
                    //check if reference number is not empty 

                    $refnumber = str_replace(array($refid, '~'), array('', ''), $line);
                if($refnumber != '') 
                    { 
                $refnumber = '_'. $refnumber .'_'; 

                $filerenamed = str_replace($find, $refnumber, $file); 
                    copy($file, $dirname . '/' . $filerenamed); 
                        } 

                echo $refnumber . "\n"; 
                    }
            }

            //close file
            fclose($handle);
        }
    }
}

我有上面的代码,可以读取包含“.5010”的文件。并将其替换为 REF*2U* 之后的字符。但是,在某些文件中存在多个 REF*2U*,是否有代码将它们拆分为一行名为“N1*PR*”并输出 2 个文件,每个文件都有自己的 REF*2U* 字符?

【问题讨论】:

    标签: php


    【解决方案1】:

    stream_get_line 可以解决问题 string stream_get_line ( 资源 $handle , int $length [, string $ending ] )

    引用文档,

    读取结束时读取长度字节,当字符串 找到了结尾指定的(不包含在返回中 值),或 EOF(以先到者为准)。

    所以循环检查特定字符串的文件行如下是一个示例:

    $i = 1;
    while(! feof($file)) {
        $contents = stream_get_line($file,1000,"REF*2U*");
        file_put_contents('new_file_'.$i.'.txt',$contents);
        $i++;
    }
    

    Similar answer

    【讨论】:

    • 它需要什么变量?
    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多