2013-01-17 40 views
1

我有一個PHP腳本,將回顯文件夾中的文件列表,並隨機顯示在我的頁面上。PHP回聲文件的網址,並從結果中刪除破折號和.php

目前,它顯示例如文件的URL:什麼燦因果齒decay.php

Qusetion:有沒有辦法去除破折號 - 從結果讓.PHP這將diplay:

什麼能引起蛀牙代替什麼燦因果齒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?> 

回答

1

的問題是雙重的:

  1. 地帶從文件擴展名,
  2. 用空格替換破折號。

下面的應該只是罰款給你:

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

參見:strtr()pathinfo()

更新

從另一個答案我收集了,你還希望選擇一個隨機設置的10個文件來顯示;下面的代碼應該這樣做:

foreach(array_slice($fileTab, 0, 10) as $file) { 
+0

感謝傑克,但有一件事我沒有考慮它是回聲沒有破折號和.php的結果,但也剝離他們從鏈接也如此onclick他們去找不到頁面。哎呀 – mally

+0

@ user1649416好吧,而不是'$ fileTab [] ='你可以寫'$ fileTab [$ file] =',然後在數組鍵中使用foreach –

+0

你好,很抱歉,但你能否再次解釋一下php dummie 。添加$ file到這裏$ fileTab [$ file] = strtr(pathinfo($ file,PATHINFO_FILENAME),' - ','');接着? – mally

0

這是你在找什麼?

$str = 'what-can-cause-tooth-decay.php'; 
$str = str_replace('.php', '', str_replace('-', ' ', $str)); 
echo $str; 
//what can cause tooth decay 
+0

你用「what-is-php.php」測試過嗎? –

+0

@Jack有趣的是'.'被忽略。固定。 – Kermit

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?> 
+0

偉大的感謝偉大的工程,但你必須很多)後'.php' – mally

+0

現在檢查它,我已經修復它爲每個短語工作 –

+0

你是非常好的謝謝 - 你知道如何得到它只顯示10個文件上頁面加載而不是健康文件夾中的所有119個文件? – mally

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)