0

PHP 4 how to strip a specific variable from the URL in this case "?lang=en"

/filename.php?lang=en

Leri
  • 12,367
  • 7
  • 43
  • 60
pwr
  • 11
  • 2
  • 1
    Using PHP4 on production is quite suicidal these days I am afraid... – Marcin Orlowski Oct 04 '12 at 11:02
  • what do you want the output to be if the url is `/filename.php?lang=en`? Also, would the output you require be different if the url was `/filename.php?lang=en&foo=bar`? – Stu Oct 04 '12 at 11:02

4 Answers4

4
$url = '/filename.php?lang=en&test=1';                    // the main link
$str = parse_url($url);                                   // parse_url
parse_str($str['query'], $arr);                           // parse_str on 'query'
unset($arr['lang']);                                      // unset 'lang'
$newQuery = http_build_query($arr);                       // rebuild query
$link = substr($url, 0, strpos($url, '?')).'?'.$newQuery; // remake link

echo $link; // /filename.php?test=1

This can be easily wrapped up into a function:

function removeParameter($link, $remove){
    $str = parse_url($link);                                    // parse_url on $link
    parse_str($str['query'], $arr);                             // parse_str on 'query'
    unset($arr[$remove]);                                       // unset $remove
    $newQuery = http_build_query($arr);                         // rebuild query
    $link = substr($link, 0, strpos($link, '?')).'?'.$newQuery; // remake link
    return $link;
}

echo removeParameter('/filename.php?lang=en&test=1', 'lang'); // /filename.php?test=1
echo removeParameter('http://www.example.com/filename.php?lang=en&test=1&me=do', 'test'); // http://www.example.com/filename.php?lang=en&me=do
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
0

You are look for the super global $_GET:

echo $_GET['lang']; // will put 'en' on the screen
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
0

Use substr() and strrpos();

$str = 'filename.php?lang=en';
$str = substr($str, 0, strrpos($str, '?'));
echo $str; // Outputs 'filename.php'
Björn
  • 29,019
  • 9
  • 65
  • 81
0

You can use the regex preg_match('/^([^?]+)/', '/filename.php?lang=en') to match everything up until the question mark.

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76