1

我有一个 php 脚本,它将回显文件夹中的文件列表并在我的页面上随机显示它们。

目前它显示文件的网址,例如:what-c​​an-cause-tooth-decay.php

Qusetion:有没有办法从结果中删除破折号 - 和 .php 以便显示:

什么会导致蛀牙而不是what-c​​an-cause-tooth-decay.php

<?php 

if ($handle = opendir('health')) {
    $fileTab = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $fileTab[] = $file; 
        }
    }
    closedir($handle);
    shuffle($fileTab);
    foreach($fileTab as $file) {
        $thelist .= '<p><a href="../health/'.$file.'">'.$file.'</a></p>';
    }
}
?>
<?=$thelist?>

谢谢

<?php 

if ($handle = opendir('health')) {
    $fileTab = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $fileTab[$file] = strtr(pathinfo($file, PATHINFO_FILENAME), '-', ' '); 
        }
    }
    closedir($handle);
    shuffle($fileTab);
    foreach(array_slice($fileTab, 0, 10) as $file) {
        $thelist .= '<p><a href="../health/'.$file.'">'.$file.'</a></p>';
    }
}
?>
<?=$thelist?>
4

4 回答 4

1

问题有两个方面:

  1. 从文件中删除扩展名,
  2. 用空格替换破折号。

以下内容对您来说应该很好:

$fileTab[] = strtr(pathinfo($file, PATHINFO_FILENAME), '-', ' ');

也可以看看:strtr() pathinfo()

更新

从我收集的另一个答案中,您还希望选择一组随机的 10 个文件来显示;下面的代码应该做到这一点:

foreach(array_slice($fileTab, 0, 10) as $file) {
于 2013-01-17T23:32:13.993 回答
0

这是你要找的吗?

$str = 'what-can-cause-tooth-decay.php';
$str = str_replace('.php', '', str_replace('-', ' ', $str));
echo $str;
//what can cause tooth decay
于 2013-01-17T23:15:51.477 回答
0
<?php 

if ($handle = opendir('health')) {
    $fileTab = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $fileTab[] = preg_replace('/\.php/', '', preg_replace('/-/i', ' ', $file));
        }
    }
    closedir($handle);
    shuffle($fileTab);
    foreach($fileTab as $file) {
        $thelist .= '<p><a href="../health/'.$file.'">'.$file.'</a></p>';
    }
}
?>
<?=$thelist?>
于 2013-01-17T23:16:55.420 回答
0

你可以试试:

$string = 'what-can-cause-tooth-decay.php';
$rep = array('-','.php');
$res = str_replace($rep,' ', $string); 

var_dump($res);

输出:

string 'what can cause tooth decay ' (length=27)
于 2013-01-17T23:20:06.230 回答