synergy989
synergy989

Reputation: 119

Remove link after last Ampersand of URL in PHP

So I see split is no good anymore or should be avoided.

Is there a way to remove the LAST Ampersand and the rest of the link.

Link Before: http://www.websitehere.com/subdir?var=somevariable&someotherstuff&textiwanttoremove

Link After: http://www.websitehere.com/subdir?var=somevariable&someotherstuff

Right now I am using this script:

<?php
    $name = http_build_query($_GET);
    // which you would then may want to strip away the first 'name='
    $name = substr($name, strlen('name='));
    //change link to a nice URL
    $url = rawurldecode($name);
?>

<?php echo "$url"; ?>

It takes the whole URL (all Ampersands included)...the issue is, the site the link is coming from adds a return value &RETURNVALUEHERE, I need to remove the last "&" and the rest of the text after it.

Thanks!

Robb

Upvotes: 0

Views: 554

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173562

If your input is already $_GET, removing the last value pair could simply be this:

http_build_query(array_slice($_GET, 0, -1));

Upvotes: 0

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

Without knowing the Real URL, I was able to come up with this:

<?php

// The string:
$string = "http://www.websitehere.com/subdir?var=somevariable&someotherstuff&textiwanttoremove";

// get the position of the last "&"
$lastPos = strrpos($string, "&");

// echo out the final string:
echo substr($string, 0, $lastPos);

Upvotes: 0

Crisp
Crisp

Reputation: 11447

using substr and strrpos

$url = substr($url, 0, strrpos($url, '&'));

Upvotes: 1

Eyal Alsheich
Eyal Alsheich

Reputation: 477

you can use strrpos() like

$url = substr($orig_url, 0, strrpos($orig_url, "&"));

Upvotes: 0

Related Questions