如何删除php中的最后一个元素

时间:2013-09-27 11:57:31

标签: php

我必须删除字符串中的最后一个元素。我在rtrim中使用了php,但它无效。

这是字符串:

 /search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC

我需要删除“& make_order = ASC”

任何人都可以帮助我吗?

9 个答案:

答案 0 :(得分:5)

$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));


编辑:

$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
//                                            ^
//                                            |_ replace , with .

答案 1 :(得分:1)

修剪应该有效:

$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");

答案 2 :(得分:1)

无法保证make_order将位于查询字符串的末尾 - 或者根本不存在。要正确删除字段,您必须使用以下内容:

$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';

// break down the URL into a path and query string
$parsed = parse_url($url);

// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);

// remove the unwanted field
unset($qs['make_order']);

// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
    $rebuilt .= '?' . http_build_query($qs);
}

echo $rebuilt;

答案 3 :(得分:0)

$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";


echo str_replace("&make_order=ASC","",$actual_link);

答案 4 :(得分:0)

$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";

$args = array_pop(explode($string, "&"));

$string = implode("&", $args);

答案 5 :(得分:0)

有很多方法。最简单的可能是:

$i=strrpos($text,'&');
$newstring=substr($text,0,$i);

答案 6 :(得分:0)

$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");

答案 7 :(得分:0)

如果&make_order=ASC总是在最后,您可以使用strstr()来执行此操作

$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);

答案 8 :(得分:0)

从网址中删除所需的密钥。

使用:

$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');

输出:

/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100

代码:

function remove_key_from_url($url, $key) {
    if (strpos($url, '?') === false) return $url;
    list($left, $right) = explode('?', $url, 2);
    parse_str($right, $get);
    if (isset($get[$key])) unset($get[$key]);
    return $left . '?' . http_build_query($get);
}