<?php
  /*
    Default document number format to convert is YMDNR for example 20080501001
    where Y - year, M - month, D - day, NR - 4 digits number.
    
    Example 1: 
      echo formatDocumentNumber('200805010001','Y/M/D/NR');
    Results:
      2008/05/01/001
      
    Example 2:
      .../formatDocumentNumber.php?dn=20080501001&f=Y/M/D%20NR 
    Results:
      2008/05/01 001
  */
  
  function formatDocumentNumber($documentNumber, $format, $d = '3') {
    $format = str_replace('CODE', '[cOdE]', $format);
    $ARR1 = array ('y', 'Y', 'M', 'D', 'NR', '[cOdE]');
    $ARR2 = array (substr($documentNumber,2,2), substr($documentNumber,0,4), substr($documentNumber,4,2), substr($documentNumber,6,2), substr($documentNumber,8));
    $ARR2[4] = sprintf("%0".$d."d",$ARR2[4]);
	$ARR2[5] = 'CODE';
    return str_replace($ARR1,$ARR2,$format);
  }
  
  if(isset($_REQUEST['dn']) && $_REQUEST['dn']!='' && isset($_REQUEST['f']) && $_REQUEST['f']!='') {
    echo formatDocumentNumber($_REQUEST['dn'],$_REQUEST['f']);
  }

  if(isset($_REQUEST['f']) && $_REQUEST['f']!='' && isset($_REQUEST['d']) && $_REQUEST['d']!='' && isset($_REQUEST['ex']) && $_REQUEST['ex']!='') {
    echo formatDocumentNumber(date("Ymd").'1',$_REQUEST['f'],$_REQUEST['d']);
  }
?>
