2014-07-17 35 views
0

如果我有多個URL,像這樣的一個變量,用戶進入所謂$urlPHP - 匹配和更換網址

http://www.example.com/home 
/home 
?home=true 
home/ 

而且這一切應該是www.example.com網站下,

哪有我將網址替換爲正確的形式?

事情是這樣的:

http://www.example.com/home => http://www.example.com/home 
/ihome      => http://www.example.com/ihome 
?home=true     => http://www.example.com/ihome?home=true 
home/      => http://www.example.com/ihome/home/ 

最後都與當前頁面/ihome

+0

告訴我們這是怎麼用的。提交一些代碼。你現在說的話可以通過解析字符串來完成,但我猜這不是你想要做的。 – simeg

+0

你想把它們連成1嗎?不知道我明白 –

+0

那些在字符串,數組,對象(基本上可以是一個數組...)等等? – Sebastien

回答

0

我假設你的問題是關於relative URLs

假設你在位置http://example.com/home,並有一個關於頁面的鏈接,該頁面被鏈接到http://example.com/about。這可通過相對鏈接<a href="about">About</a>在'home.php'(或任何/ home託管的地方)內訪問。這遵循標準的目錄協議,並且不會有太大的改變。我提供的鏈接中提供了大量這些示例以獲取更多信息。

編輯:最初的問題太模糊了,因爲我的答案對這個問題真正需要的答案是真實的。正確答案,如何更換,如下。

使用str_replace(),如下面的註釋所示。例如,如何轉換「/ ihome」。假設我們在位置http://example.com/about

$body = ...; // assuming this is going through whole php document 

$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; 
$tokens = explode('/', $url); 
array_pop($tokens); // remove "/about" 
$url = implode("", $tokens); 
str_replace("/ihome", $url . "/ihome", $body); 

最後一行肯定有爭議,但這應該起作用。如果你想要檢查多個鏈接,你可能想要使用正則表達式的方法(即任何被定義爲「/ sub」或任何查詢「query」的鏈接)。

+0

是的,但我如何替換它們? –

+0

'str_replace();' – Sebastien

0

Theres可能是一種在每個循環中用一個preg_replace函數完成此操作的方法,但是像這樣的事情應該可以做到。

<?php 

foreach($urls as $key => $val) 
    if(!preg_match('/^http\:\/\/www\.example\.com\//', $val)) 
     $url[$key] = 'http://www.example.com/'.ltrim($val, '/');