2013-10-14 22 views
0

我需要爲我正在執行的腳本動態創建標題,標題應取決於當前正在使用的文件。不同的標題取決於什麼file.php當前正在使用

我的結構腳本是:

@require_once"bd.php"; 
@require_once"Funciones/functions.php"; 
include head.php; 
include body.php; 
include footer.php; 

我的標題功能的代碼是從head.php

稱這是我的功能,但不工作總是返回空白的結果:■

function get_title(){ 
    $indexurl = "index.php"; 
    $threadurl = "post.php"; 
    $searchurl = "search.php"; 
    $registerurl = "register.php"; 

    $query = $_SERVER['PHP_SELF']; 
    $path = pathinfo($query); 
    $url = $path['basename']; //This returns the php file that is being used 

    if(strpos($url,$indexurl)) { 
     $title = "My home title"; 
    } 
    if(strpos($url,$threadurl)) { 
     $title = "My post title"; 
    } 
    if(strpos($url,$searchurl)) { 
     $title = "My search title"; 
    } 
    if(strpos($url,$registerurl)) { 
     $title = "My register page title"; 
    } 

return $title; 
} 

我呼叫功能:

<title><? echo get_title(); ?></title> 
+0

什麼是$ url實際返回?你有沒有測試過它返回的php文件名? –

+0

是的$ url正確返回:index.php,post.php,search.php和register.php取決於正在使用的文件。 –

+0

你應該做'strpos($ url,$ indexurl)!== FALSE',而不是假設它返回一個整數。因爲如果它的第一個出現strpos將返回0,那麼你的if語句轉換爲false。 – vinsanity38

回答

-1

我發現這個問題:

$string = "This is a strpos() test"; 

if(strpos($string, "This)) { 
    echo = "found!"; 
}else{ 
    echo = "not found"; 
} 

如果嘗試執行,你會發現,它輸出「未找到」,儘管「這個」在$字符串很清楚的是。這是另一個大小寫敏感問題嗎?不完全的。這次問題在於「This」是$ string中的第一件事,這意味着strpos()將返回0。但是,PHP認爲0與false的值相同,這意味着我們的if語句不能告訴「未找到子字符串」和「在索引0處找到子字符串」之間的區別 - 非常麻煩!

所以,在我的情況下,使用strpos正確的方法是從$ indexurl,$ threadurl,$ searchurl和$ REGISTERURL

function get_title(){ 
    $indexurl = "ndex.php"; 
    $threadurl = "ost.php"; 
    $searchurl = "earch.php"; 
    $registerurl = "egister.php"; 

    $query = $_SERVER['PHP_SELF']; 
    $path = pathinfo($query); 
    $url = $path['basename']; //This returns the php file that is being used 

    if(strpos($url,$indexurl)) { 
     $title = "My home title"; 
    } 
    if(strpos($url,$threadurl)) { 
     $title = "My post title"; 
    } 
    if(strpos($url,$searchurl)) { 
     $title = "My search title"; 
    } 
    if(strpos($url,$registerurl)) { 
     $title = "My register page title"; 
    } 

return $title; 
} 
+0

你做錯了。見上面的其他答案。 http://stackoverflow.com/a/19353179/472768 – FeifanZ

+0

你可以測試該鏈接裏面的代碼?,不起作用,第一個字符不考慮。 –

+0

我在生產站點的相同情況下使用精確的代碼。不確定「第一個字符沒有考慮到」是指 – FeifanZ

2

一個更好的方法去除第一個字符可以在這裏找到一個我說在我的最初評論中: https://stackoverflow.com/a/4858950/1744357

您應該對strpos使用標識屬性並對FALSE進行測試。

if (strpos($link, $searchterm) !== false) { 
    //do stuff here 
} 
+0

你可以測試你的代碼,它同樣不起作用 –

相關問題