2012-01-16 15 views
0

的第二部分的PHP陣列功能可用於將一個字符串匹配分隔線的第一部分並返回分隔線的第二部分?我使用數組的原因是因爲我在文件中有許多分隔文本行。例如:的PHP陣列功能應該是用來匹配一個字符串分隔線的第一部分和返回分隔線

contact-us.php = Contact Us- Test Bed 

我需要一些方法來匹配網頁文件名的分隔線的第一部分,並返回它的第二部分。我已經嘗試了幾個不同的數組函數,但是我不知道要使用哪一個函數或者如何實現數組函數,前提是我找到了正確的數組函數。這是我設計的代碼,它位於php文件的頭部。一旦選擇了正確的頁面標題,我會將其打印到標題標籤中。

function getPageName() 
{ 
    return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); // If one echo's this and the url is /TestBed/contact-us.php Output will be: contact-us.php 
} 

function pageTitleIdentifier() 
{ 
    $filename = 'http://localhost/TestBed/includes/apptop/title.txt'; 
    $mode = 'rb'; 
    $file_handle = fopen ($filename, $mode); 

    while (!feof($file_handle)) { 
     $page_title_pair = fgets($file_handle); // This will start reading where the above while loop stopped line by line. 
     $parts = explode('=', $page_title_pair); 
     @ $pageTitle = $parts[0] . $parts[1]; // Part zero is the filename ex contact-us.php Part one is the Title ex Contact Us- Test Bed for that page. 
    } 

    fclose($file_handle); 
} 

那麼,這樣做的正確方法是什麼?非常感謝你!

回答

0

首先,你可能要考慮實施的緩存解決方案。要爲每個請求解析文件,在高流量服務器上,肯定會添加不必要的負載。

試試這個:

function pageTitleIdentifier() 
{ 
    $filename = 'http://localhost/TestBed/includes/apptop/title.txt'; 
    $mode = 'rb'; 
    $file_handle = fopen ($filename, $mode); 

    while (!feof($file_handle)) { 

     $page_title_pair = fgets($file_handle); 

     list($script, $title) = explode('=', $page_title_pair); 

     // Uncomment below lines for debugging, they must line up exactly 
     // for the condition to be met, breaking the loop 
     // var_dump($script); 
     // var_dump(getPageName(); 

     // Because we reading from a file, might be some whitespace issues 
     // trim and strtolower ensures a true apples to apples comparison 
     if (trim(strtolower($script)) === trim(strtolower(getPageName()))) { 
      return $title; 
     }    
    } 

    fclose($file_handle); 
} 
+0

@MindMaster:這篇對你的工作? – 2012-01-17 22:07:25

+0

嗯。它不工作。它不會給出任何錯誤,即使它設置爲「通知」。我改變了這一行'print_r(list($ page,$ title)= explode('=',$ page_title_pair));'它打印這個:Array([0] => index.php [1] =>測試牀)陣列([0] => news.php [1] =>新聞 - 測試牀)Array([0] => contact-us.php [1] =>聯繫我們 - ] => about.php [1] =>關於 - 測試牀)每一行都是一個新的數組,但是我認爲在$ title讀取所有文件後,$ script被檢查。我將如何改變它,以便只讀取一行,然後進行比較? – MindMaster 2012-01-17 22:47:02

+0

做一個var_dump(getPageName())併發布結果。 – 2012-01-17 22:54:23