Search code examples
phpparsingreadfileglob

How to get file contents from a specific file name in directory?


I've created a PHP script that pulls the extension '.mov' into the script and then parses the data. But the problem is, is that I have a directory with a bunch of .mov files, and the script is pulling the last one only.

In other words, I have a directory with "Keating651.mov" "NickSHC809.mov" "Vill230.mov" and more... Can I change my code to have it pull from a directory and pull the file that matches "NickSHC809"... then run the script? And if I change it to pull "Keating651" at a later time, it only pulls that file?

foreach (glob('*.mov') as $filename){
    $theData = file_get_contents($filename) or die("Unable to retrieve file data");
}

$string = $theData;
$titles = explode("\n", $string);

function getInfo($string){
    $Ratings = ['G', 'PG', 'PG-13', 'R', 'NR', 'XXX'];
    $split = preg_split("/\"(.+)\"/", $string, 0, PREG_SPLIT_DELIM_CAPTURE); 
    if(count($split) == 3){ 
        preg_match("/(".implode("|", $Ratings).")\s/", $split[0], $matches);
        $rating = $matches[0];
        return ["title" => $split[1], "rating" => $rating];
    }
    return false;
}


$infolist = array();
foreach($titles as $title){
    $info = getInfo($title);
    if($info !== false){
    $infolist[] = $info;
    }
}

usort($infolist, "infosort");

function infosort($lhs,$rhs) {
  return strcmp($lhs['rating'], $rhs['rating']);
}

foreach ($infolist as $info) {
        echo "<div style ='margin-bottom: 3px; text-align: center;
          font:13px Verdana,tahoma,sans-serif;color:green;'> 
           {$info["title"]} : {$info["rating"]}</div>";
}

echo "<div style='text-align:center; margin-top: 20px;'><img src='shclogo.png'
alt='Logo' width='200' height='133'/></div>";

?>

Solution

  • Not sure I understand the question. You just want the content of that one specific file, and then manually change the file to get? Then you could just change this

    foreach (glob('*.mov') as $filename){
      $theData = file_get_contents($filename) or die("Unable to retrieve file data");
    }
    

    To

    $theData = file_get_contents("NickSHC809.mov") or die("Unable to retrieve file data");
    

    EDIT

    As per your comment, try

    $matchedFiles = array();
    foreach (glob('*.mov') as $filename){
      if (preg_match("/^(NickSHC809|Keating651)/i",$filename))
        $matchedFiles[] = $filename;
    }
    $useFile = reset($matchedFiles); // If you know there's just one file, otherwise do something to select the correct one
    $theData = file_get_contents($useFile) or die("Unable to retrieve file data");