3

I want to remove the first folder outputted by $_SERVER['REQUEST_URI'];

// I use it as language switcher in my website, here's how it works:

<?php $currenturl=$_SERVER['REQUEST_URI']; ?>

<a href="https://mysite.com/<?php echo $currenturl ?>">United States</a>
<a href="https://mysite.com/ca<?php echo $currenturl ?>">Canada</a>
<a href="https://mysite.com/br<?php echo $currenturl ?>">Brasil</a>

The problem is, in Canada for example, it outputs:

https://mysite.com/ca/ca/mypage

It should be

https://mysite.com/ca/mypage

anubhava
  • 761,203
  • 64
  • 569
  • 643
Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86

4 Answers4

2

well, I think you are trying to get the filename of a path instead of removing the first folder. try the following code:

$currenturl=basename($_SERVER['REQUEST_URI']);
jhdxr
  • 166
  • 1
  • 4
1

Make use of str_replace

<?php 

$currenturl=$_SERVER['REQUEST_URI'];
$currenturl=str_replace('/ca','',$currenturl); // I have added it here

?>

<a href="https://mysite.com/<?php echo $currenturl ?>">United States</a>
<a href="https://mysite.com/ca<?php echo $currenturl ?>">Canada</a>
<a href="https://mysite.com/br<?php echo $currenturl ?>">Brasil</a>
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

The $_SERVER['REQUEST_URI'] is provided by php, and it's not something that you can simply remove from your htaccess file. You need to remove it in php:

<?php $currenturl=preg_replace('#(/[a-z]{2})?(/.*)#','${2}',$_SERVER['REQUEST_URI']); ?>
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
0

I use slightly modified example from Shankar Damodaran -

<?php
    $currenturl = $_SERVER['REQUEST_URI'];
    $languge_folder  = array('/en', '/ru', '/ua');
    $currenturl_en = str_replace($languge_folder,'',$currenturl); 
    $currenturl_ru = str_replace($languge_folder,'',$currenturl);
    $currenturl_ua = str_replace($languge_folder,'',$currenturl);
?>
          <select id="select-language" onchange="window.location.href=this.value">
             <option value="/ua/<?php echo $currenturl_ua; ?>"  selected="selected">Ukrainian</option>
             <option value="/ru/<?php echo $currenturl_ru; ?>" >Russian</option>
             <option value="/en/<?php echo $currenturl_en; ?>" >English</option>
          </select>
TheRock
  • 1
  • 2