//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 *字符?
答案 0 :(得分:1)
stream_get_line可以解决问题 string stream_get_line(resource $ 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++;
}