下面的代码将回显每个文件中的关键字,是否可以获取结果(每个文件中的关键字)以按字母顺序显示。
<?php
$files = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$selection = $files;
$files = array();
$keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = '"(.*?)'"/i", $content, $matches);
$keywords = $matches[1];
}
$results .= '<li><a href="http://domain.com/' . htmlentities($file, ENT_QUOTES) . '">'.$keywords.'</a></li>';
}
?>
<?=$results?>
使用 sort()
对关键字 array 进行排序:
$keywords = array();
// ...
$keywords[] = $matches[1];
sort($keywords);
>在$keywords上使用sort()。 有一些拼写错误和未使用的变量。 在所有文件都处理完毕之前,您不需要构建$results HTML,因此请将 $results = '' 移出处理文件的 foreach 循环,然后对关键字进行排序,然后构建$results。
<?php
$selection = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$files = array();
// $keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
//$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = '"(.*?)'"/i", $content, $matches);
$keywords[] = $matches[1];
}
}
$results = '';
sort($keywords); //comment this out to see the effects of the sort()
foreach($keywords as $_k) {
$results .= '<li><a href="http://domain.com/' . htmlentities($file, ENT_QUOTES) . '">'.$_k.'</a></li>';
}
?>
<?=$results?>