URL上的PHP str_replace

时间:2009-10-15 09:02:16

标签: php

我想从给定的网址中删除“& start = 2”。 这就是我试过的:

$uri = "http://test.com/test/?q=Marketing&start=2";

$newuri = str_replace("&start=","",$url);

echo $newuri;

6 个答案:

答案 0 :(得分:6)

您需要使用preg_replace代替:

$newuri = preg_replace('/&start=(\d+)/','',$uri);

答案 1 :(得分:3)

您将$ url作为参数传递给str_replace。但是具有url的变量称为$ uri。

$uri = "http://test.com/test/?q=Marketing&start=2";

$newuri = str_replace("&start=2","",$uri);

...

答案 2 :(得分:1)

只是为了抛出一个无正则表达式的解决方案:

// Grab the individual components of the URL
$uri_components = parse_url($uri); 

// Take the query string from the url, break out the key:value pairs
// then put the keys and values into an associative array
foreach (explode('&', $uri_components['query']) as $pair) {
    list($key,$value) = explode('=', $pair);
    $query_params[$key] = $value;
}

// Remove the 'start' pair from the array and start reassembling the query string
unset($query_params['start']);
foreach ($query_params as $key=>$value)
    $value ? $new_query_params[] = $key."=".$value : $new_query_params[] = $key;

// Now reassemble the whole URL (including the bits removed by parse_url)
$uri_components['scheme'] .= "://";
$uri_components['query'] = "?".implode($new_query_params,"&");
$newuri = implode($uri_components);

不可否认,与基于正则表达式的解决方案相比,它是非常冗长的,但它可能提供一些额外的灵活性?

答案 3 :(得分:0)

请记住,如果更改了查询字符串元素的位置,它仍然是一个有效的URI。因此,start参数可能是第一个,因此可能会以?而不是&开头。

所以这个正则表达式涵盖了两种情况:

preg_replace("#[\?&]start=\d+#", '', $uri)

答案 4 :(得分:0)

试试这个正则表达式免费解决方案:

$uri = "http://test.com/test/?q=Marketing&start=2";
$QueryPos = strpos($uri, '&start='); //find the position of '&start='
$newURI = substr($uri, 0, -(strlen($uri)-$QueryPos)); //remove everything from the start of $QueryPos to end
echo $newURI; //OUTPUT: http://test.com/test/?q=Marketing

答案 5 :(得分:0)

if(isset($_GET['start']))

{

   $pageNo = $_GET['start'];

   $TmpString = '&start='.$pageNo;

  $newuri = str_replace($TmpString,"",$url);

  // removed "&start=2"

  echo $newuri;

}