//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*字符?
stream_get_line就可以了字符串stream_get_line(资源$handle, int $length [, String $ending])
引用文档
读取结束时,长度字节已读取,当字符串找到由ending指定的(不包含在返回中)值),或EOF(以先到者为准)。
那么循环检查特定字符串的文件行,如下所示是一个例子:
$i = 1;
while(! feof($file)) {
$contents = stream_get_line($file,1000,"REF*2U*");
file_put_contents('new_file_'.$i.'.txt',$contents);
$i++;
}
类似回答