2014-01-23 47 views
-1

從php中刪除一些詞語?從php中刪除一些詞語?

首次訪問頁面例如

www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success 

從我的PHP代碼,我會得到$curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success

,我希望得到$curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999

(切&message=success

我該怎麼辦?

<?PHP 
    $current_link = "$_SERVER[REQUEST_URI]"; 
    $curreny_link_redirect = substr($current_link,1); 
    $curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect); 
    echo $curreny_link_redirect_new; 
?> 
+2

您確定使用$ current_link =「$ _SERVER [REQUEST_URI]」; ? 它必須是$ current_link = $ _SERVER [「REQUEST_URI」]; – zerokavn

+1

@zerokavn那實際上應該是正確的。 –

+0

爲什麼你不用''_GET'數組而不是'REQUEST_URI'? – Barmar

回答

1

str_replace電話是什麼應該相反。你想要替換的應該是第一個參數,而不是第二個參數。

//Wrong 
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect); 

//Right 
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect); 
0

做這樣

<?php 
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
echo $str = array_shift(explode('&',$str)); 
0

也許不是一個答案,但對於以後的訪問者免責聲明:

1)我會強烈建議功能:http://pl1.php.net/parse_url。 而在這種情況下:

$current_link = "$_SERVER[REQUEST_URI]"; 
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY)); 
print_r($arguments); 

2)建立新的URL,使用http://pl1.php.net/manual/en/function.http-build-url.php。這是我認爲最好的,未來的修改就緒解決方案。

在這種情況下,這個解決方案有點矯枉過正,但是這些功能真的很棒,值得在這裏介紹。

問候

0

試試這個:

$current_link_path = substr($_SERVER['PHP_SELF'], 1); 
$params = $_GET; 
if ($params['message'] == 'success') { 
    unset($params['message']); 
} 
$current_link_redirect = $current_link_path . '?' . http_build_query($params); 
1

雖然簡單的方式做,這是使用正則表達式(或者甚至str_replace()靜態),我建議使用內置的URL處理功能。用複雜的參數或多個參數時,這可能是有用的:

$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success'; 
$url = parse_url($data); 
parse_str($url['query'], $url['query']); 

//now, do something with parameters: 
unset($url['query']['message']); 
$url['query'] = http_build_query($url['query']); 
$url = http_build_url($url); 

- 請,音符,即http_build_url()是PECL函數(pecl_http要準確)。上面的方法可能看起來更復雜,但它有好處 - 首先,正如我已經提到的,這將很容易修改爲處理複雜參數或多個參數。其次,它將產生有效的URL - 即編碼諸如斜線,空格,e t.c之類的東西。 - 結果。因此,結果將永遠是正確的網址。

+0

很好的答案。我是第一個,但你更完整。 +1 :)。 –