shumonira Posted November 9, 2016 Share Posted November 9, 2016 hi I have a form to upload file. this will upload the text file. suppose 0521_2145.txt. the 1st 4 digits are the serial number. so can I get these 1st 4 digits as serial number for the Serial Number field? thank you Quote Link to comment Share on other sites More sharing options...
ginerjm Posted November 9, 2016 Share Posted November 9, 2016 (edited) yes you can. After your php code has processed the uploaded file and saved it using the true filename and not the temporary filename that was generated by the upload, you can use a PHP string function to grab whatever portion of that filename that you want and then do whatever you want to do with that value. Edited November 9, 2016 by ginerjm Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted November 9, 2016 Solution Share Posted November 9, 2016 Both these will do it $serialno = strstr($filename, '_', true); // get chars before the '_' $serialno = substr($filename, 0, 4); // get first four chars Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted November 9, 2016 Share Posted November 9, 2016 You need to combine the number extraction with validation. Users make mistakes. And some users even purposely break the applications of unsuspecting programmers. <?php /* * I don't know the exact pattern, so I'm guessing it's always 4 digits followed by an underscore, another 4 digits and * the extension. Change if necessary. */ const FILENAME_PATTERN = '/\\A(?<serial>\\d{4})_\\d{4}\\.txt\\z/i'; $filename = '0521_2145.txt'; // test $filename_parts = null; if (preg_match(FILENAME_PATTERN, $filename, $filename_parts)) { $serial_number = $filename_parts['serial']; echo 'The serial number is '.htmlspecialchars($serial_number, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } else { echo 'Invalid filename!'; } Quote Link to comment Share on other sites More sharing options...
ginerjm Posted November 9, 2016 Share Posted November 9, 2016 Jacques has provided the better answer in this particular case. The rule is "Never Trust The User's Input" which he is attempting to solve for you. Barand has given you the purely mechanical solution to your question, but J has given you valuable code to build a better app. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.