【问题标题】:Unexpected output for filename文件名的意外输出
【发布时间】:2016-08-29 13:14:05
【问题描述】:
<?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);
        }
    }
}

?>

我有这段代码,输出应该是“.5010”的替换。最终名称中带有“ref”,但是,当我运行代码时,它只显示了 ref 而不是文件名的其余部分,我在我的计算机 putty 上尝试了它,结果发现有一个 ”?”在参考号之后,有什么办法可以解决这个问题吗?

例如;我的文件是 4867586.5010.476564.ed

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

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

【问题讨论】:

  • 我不明白,“?”在哪里?来自(哪里?你想达到什么目的?您还应该提供当前目录结构和文件的示例、当前代码的内容以及您希望它的外观。
  • 好的,请检查一下,我修好了。我认为这是因为我使用的是旧版本的 php,所以有没有办法可能就是问题所在,以及如何解决它? @路人
  • 此问题很可能与此行有关:$refnumber = str_replace(array($refid, '~'), array('', ''), $line);。您能否确认 .ed 文件不包含任何“?”还是无效字符?
  • 它也有可能停在“4867586_SMIL01”,因为它后面有一个换行符,它被替换为“?”。所以4867586_SMIL01\n_476564.ed 在你的字符串替换后变成了4867586_SMIL01?_476564.ed。要进一步了解问题,您唯一真正的选择是提供带有文件的完整工作示例。或者通过 xdebug 运行代码。

标签: php


【解决方案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 变量。

【讨论】:

  • 嘿,你能看看我的另一个问题,如果不是太麻烦的话?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2011-12-20
  • 2017-08-26
  • 1970-01-01
  • 2015-08-20
相关资源
最近更新 更多