我有一个php脚本,它将从文件夹中回显文件列表,并在我的页面上随机显示它们。
现在显示文件的url,例如:what-can-cause-tooth-decay.php
问题:是否有一种方法可以从结果中删除-和。php,以便显示:
什么能引起蛀牙代替what-can-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?>
问题是双重的:
- 从文件中删除扩展名,
- 用空格代替破折号
下面的代码应该可以正常工作:
$fileTab[] = strtr(pathinfo($file, PATHINFO_FILENAME), '-', ' ');
参见:strtr()
pathinfo()
我从另一个答案中收集到,您还希望随机选择一组10个文件来显示;下面的代码应该做到这一点:
foreach(array_slice($fileTab, 0, 10) as $file) {
你可以试试:
$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)
这是你要找的吗?
$str = 'what-can-cause-tooth-decay.php';
$str = str_replace('.php', '', str_replace('-', ' ', $str));
echo $str;
//what can cause tooth decay
<?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?>