文件名的意外输出

时间:2016-08-29 13:14:05

标签: php

<?php 
error_reporting(E_ALL);
ini_set('display_errors' ,1);

//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);
        }
    }
}

?>

我有这个代码,输出应该是&#34; .5010的替换。&#34;与&#34; ref &#34;但是,在最后的名字中,当我运行代码时,它只是向我显示ref而不是文件名的其余部分,我在我的计算机腻子上尝试了它并且在那里&#39; sa&#34;?&# 34;在参考编号之后,有什么办法可以解决这个问题吗?

例如;我的档案是4867586.5010.476564.ed

代码执行并读取文件后,输出应为:4867586_SMIL01_476564.ed,而不是:4867586_SMIL01

当我在putty上检查时,文件名是:4867586_SMIL01?_476564.ed

1 个答案:

答案 0 :(得分:1)

文件名中的?表示refnumber行中某处有non-printable字符。

这很可能是一个行尾字符或其他内容。 如果它是前者,则可以通过更改行来解决:

$refnumber = str_replace(array($refid, '~'), array('', ''), $line);

$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber); // remove any whitespaces or line endings.

如果是后者,那么您需要使用在线提供的文件清理程序功能之一来清理$refnumber变量。