We help IT Professionals succeed at work.
Get Started

My output has a "?" on the name and the file doesn't open anymore

Jazzy 1012
Jazzy 1012 asked
Last Modified: 2016-08-30
ini_set('display_errors' ,1);

//expression to be found in file name
$find = '.5010.';

//directory name
//we will store renamed files here
$dirname = '5010';
    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))

    $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
Watch Question
Most Valuable Expert 2011
Author of the Year 2014
This problem has been solved!
Unlock 1 Answer and 14 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE