2013-01-21 57 views
2

在我的論壇URL中,其中存在「index.php」。我想用「測試」來替換它。在我的PHP文件,我有這樣一行:使用preg_replace要更改index.php要測試

// Makes it easier to refer to things this way. 
    $scripturl = $boardurl . '/index.php'; 

我嘗試了將其更改爲:

// Makes it easier to refer to things this way. 
    $scripturl = $boardurl . '/test'; 

然而,返回404錯誤。我被告知我需要使用preg_replace來實現這一點。我看了一下PHP手冊,它說我需要一個模式,替換和一個主題。我對主題部分感到困惑。

我想這一點,但沒有得勝

// Makes it easier to refer to things this way. 
    $scripturl = $boardurl . preg_replace('/index.php','/test','?'); 

下面是一個例子URL: 「domain.com/index.php?node=forum」

我希望它看起來像「 domain.com/test?node=forum「

+0

你試過用'/ test /'而不是'/ test'嗎?這可能是你的問題。 – Charles

+0

是的,但仍然是同樣的問題。 – Xarcell

+0

不會str_replace更容易爲您的目的? http://php.net/manual/en/function.str-replace.php另外,你有沒有嘗試迴應你創建的字符串,以確保他們看起來你期望他們? – lostphilosopher

回答

3

您可以使用str_replace()。就像這樣:

$new_url = str_replace('index.php', 'test/', $original_url); 

注意preg_replace()會做的工作太多,但它更復雜(強大)。 str_replace()適用於這種情況。

僅供參考,str_replace的主題參數是原始字符串,在您的示例中爲帶有'index.php'的url。你的例子看起來像:

$pattern = '/index\.php/'; 
$replacement = 'test/'; 
$subject = 'http://yoursite.com/index.php?foo=bar'; 

echo preg_replace($pattern, $replacement, $subject); 
+0

我不確定OP是否真的希望PHP代碼執行查找替換。 (也許)他想對PHP代碼本身進行查找替換。 –

+0

如果是這樣,他應該放下評論 – hek2mgl

+0

我對如何實現我的目標感到困惑。感謝這個例子,現在對我來說很有意義。雖然,我不認爲我可以在我的情況下使用它。另一個人告訴我,我只是改變「$ scripturl = $ boardurl。'/index.php';」到「$ scripturl = $ boardurl。'/ test';」然後把我的htaccess中的東西正確地執行任何事情。 – Xarcell