Search code examples
phppreg-match

Preg matching $_FILES


I want to capture the scans from $_FILES, because there will be always passed an empty scan input name and the varry of other can change, I need to get the $_FILES name's and the number. Do you have any advice how to accomplish that?

// Skipping the empty scan, and getting the 0-100 possible
$results = preg_grep('/^scan\d{1,2}$/', $_FILES);

Generates Array to string conversion error

The post dump

["scan0"]=>
  array(5) {
    ["name"]=>
    string(6) "2.jpeg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(24) "C:\xampp\tmp\phpD7B4.tmp"
    ["error"]=>
    int(0)
    ["size"]=>
    int(24618)
  }
  ["scan1"]=>
  array(5) {
    ["name"]=>
    string(6) "2.jpeg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(24) "C:\xampp\tmp\phpD7B5.tmp"
    ["error"]=>
    int(0)
    ["size"]=>
    int(24618)
  }
  ["scan"]=>
  array(5) {
    ["name"]=>
    string(0) ""
    ["type"]=>
    string(0) ""
    ["tmp_name"]=>
    string(0) ""
    ["error"]=>
    int(4)
    ["size"]=>
    int(0)
  }

Solution

  • $scankeys = [];
    
    foreach($scans as $key => $scan)
    {
      if(preg_match("/^scan[0-9]{1,2}$/", $key)){
        $scankeys[] = $key;
      }
    }
    

    I should mention that this is better than trying to combine multiple array manipulation functions to achieve the same result.