title: PHP - Explode/ substr/ Filename
body: <p>See previous Question which was partly answered but there has been a change in requirements for the script: <a href="https://stackoverflow.com/questions/26588225/php-exploding-moving-filename/26588832?noredirect=1#comment42018497_26588832">PHP - Exploding / Moving / Filename</a></p>
  
  <p>i'm new to php and am stuck. I have loads of files that look like this:</p>
  
  <p>2014-04-01 NS122345 - The date, the initials of the person and there employee code.</p>
  
  <p>I want to be able to move the files that have NS or JB Or GA into there relevant folder/directories. So for NS it would go into the Nathan Saunders Folder, for JB into the Joe Bailey folder.</p>
  
  <p>My directory structure looks like this:</p>
  
  <pre><code>root/wan/upload - Where files/images/docs are stored. Inside upload folder i have:
  &gt;2014-04-08 NS6565.doc
  &gt;2012-01-03 JB8932.doc
  &gt;2013-02-01 GA5434.doc
  &gt;etc
  root/wan/administrator/components/com_upload - where my code is stored
  </code></pre>
  
  <p>This is my php code for moving, creating and checking the filename and putting it in the correct folder: </p>
  
  <pre><code>$dir    = JPATH_BASE . DS . "upload";
  $folders = array('SE528733B'=&gt;'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/528733B','SE125673B'=&gt;'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/125673B','SE3452312'=&gt;'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/3452312');
  $files  = scandir($dir);
  foreach($files AS $file){
      if(!is_file($dir.DS.$file)){ continue; }
      $array = explode(' ', $file); 
      if(count($array)&lt;2){ continue; }
      $firstTwoLetters = substr($array[1], 0, 9);
      $foldername = $firstTwoLetters;
          if(is_dir($folders[$firstTwoLetters])||mkdir($foldername[$firstTwoLetters],0777, 1)) 
              rename($dir.DS.$file,$foldername[$firstTwoLetters].DS.$file);
  </code></pre>
  
  <p>That code currently reads the filename if its already in the array "folders" it moves to the correct folder, I have changed it recently to make the folder automatically reading whatever file is in the upload section, but the problem comes when making the folder, the mkdir seems to make the directory:</p>
  
  <p>1) in the wrong place it makes it where the code is stored which is in the com_upload section instead of making it in the upload folder.
  2) Names it wrong it takes the first letter not the letters or numbers after it. E.g. "2014-04-08 NS6565.doc", makes the directory "N"</p>
  
  <p>Any help to fixing those 2 problems would be great. </p>
  
  <p>Thanks,</p>