Search code examples
phprequest-uri

Remove parent folder from $_SERVER['REQUEST_URI'];


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


Solution

  • 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>