如何从目录中的特定文件名获取文件内容?

时间:2013-06-07 16:49:59

标签: php parsing readfile glob

我创建了一个PHP脚本,将扩展名“.mov”拉入脚本,然后解析数据。但问题是,我有一个带有一堆.mov文件的目录,而脚本只是拉动最后一个。

换句话说,我有一个目录,其中包含“Keating651.mov”“NickSHC809.mov”“Vill230.mov”以及更多...我可以更改我的代码,让它从目录中拉出并拉出匹配的文件“NickSHC809”......然后运行脚本?如果我把它更改为稍后拉“Keating651”,它只会拉那个文件?

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>";

?>

1 个答案:

答案 0 :(得分:0)

不确定我理解这个问题。您只需要该特定文件的内容,然后手动更改文件以获取?然后你可以改变这个

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

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

修改

根据您的评论,请尝试

$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");