譯 文:如大家所知php對于用數據庫驅動的網站(making database-driven sites)來講可謂功能強大,可是我們是否可以用它來做點其他事情呢?php給了我們所有我們期望的工具:for與while的循環結構、數學運算等等,還可以通過兩種方式來引用文件:直接引用或向服務器提出申請。其實何止這些,讓我們來看一個如何用它來做導航條的例子:完整的原代碼:
<!—— this "<?" is how you indicate the start of a block of php code, ——>
<?php # and this "#" makes this a php comment.
$full_path = getenv("request_uri");
$root = dirname($full_path);$page_file = basename($full_path);$page_num = substr($page_file, strrpos($page_file, "_") + 1, strpos($page_file, ".html") - (strrpos($page_file, "_") + 1));
$partial_path = substr($page_file, 0, strrpos($page_file, "_"));
$prev_page_file = $partial_path . "_" . (string)($page_num-1) . ".html";$next_page_file = $partial_path . "_" . (string)($page_num+1) . ".html";
$prev_exists = file_exists($prev_page_file);$next_exists = file_exists($next_page_file);
if ($prev_exists)
{ print "<a href="$root/$prev_page_file">previous</a>";if ($next_exists)
{ print " | ";} if ($next_exists)
{ print "<a href="$root/$next_page_file">next</a>";}
?>//原程序完。
代碼分析:ok! 前面做了足夠的鋪墊工作,現在讓我們來看看如何來用php來完成這項工作:
<!—— this "<?" is how you indicate the start of a block of php code, ——> <?php # and this "#" makes this a php comment.
$full_path = getenv("request_uri");
$root = dirname($full_path);$page_file = basename($full_path);
/* php函數getenv()用來取得環境變量的值,request_uri的值是緊跟在主機名后的部分url,假如url是http://www.yourmom.com/dinner/tuna_1.html, 那它的值就為/dinner/tuna_1.html. 現在我們將得到的那部分url放在變量$full_path中,再用dirname()函數來從url中抓取文件目錄,用basename()函數取得文件名,用上面的例子來講dirname()返回值:/dinner/;basename()返回:tuna_1.html.接下來的部分相對有些技巧,假如我們的文件名以story_x的格式命名,其中x代表頁碼,我們需要從中將我們使用的頁碼抽出來。當然文件名不一定只有一位數字的模式或只有一個下劃線,它可以是tuna_2.html,同樣它還可以叫做tuna_234.html甚至是candy_apple_3.html,而我們真正想要的就是位于最后一個“_”和“。html”之間的東東。可采用如下方法:*/ $page_num = substr($page_file, strrpos($page_file, "_") + 1, strpos($page_file, ".html") - (strrpos($page_file, "_") + 1));/* substr($string, $start,[$length] )函數給了我們字符串$string中從$start開始、長為$length或到末尾的字串(方括號中的參數是可選項,如果省略$length,substr就會返回給我們從$start開始直到字符串末尾的字符串),正如每一個優秀的c程序員告訴你的那樣,代表字符串開始的位置開始的數字是“0”而不是“1”。
函數strrpos($string, $what)告訴我們字符串$what在變量$string中最后一次出現的位置,我們可以通過它找出文件名中最后一個下劃線的位置在哪,同理,接著的strpos($string, $what)告訴我們“。html”首次出現的位置。我們通過運用這三個函數取得在最后一個“_”和“。html”之間的數字(代碼中的strpos()+1代表越過“_”自己)。
剩下的部分很簡單,首先為上頁和下頁構造文件名:*/ $partial_path = substr($page_file, 0, strrpos($page_file, "_"));
$prev_page_file = $partial_path . "_" . (string)($page_num-1) . ".html";$next_page_file = $partial_path . "_" . (string)($page_num+1) . ".html";
/*(string)($page_num+1)將數學運算$page_num+1的結果轉化為字符串類型,這樣就可以用來與其他字串最終連接成為我們需要的文件名。
*/ /*現在檢查文件是否存在(這段代碼假設所有的文件都位于同樣的目錄下),并最終給出構成頁面導航欄的html代碼。
*/ $prev_exists = file_exists($prev_page_file);$next_exists = file_exists($next_page_file);
if ($prev_exists)
{ print "<a href="$root/$prev_page_file">previous</a>";if ($next_exists)
{ print " | ";} if ($next_exists)
{ print "<a href="$root/$next_page_file">next</a>";}
?>
新聞熱點
疑難解答