Skip to content
Advertisement

PHP: Change only a portion of a URL string?

I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.
I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the “” to separate it (I tried that but have problems by using explode("", $string)) and then replace the last low with high

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere
Mestika

Advertisement

Answer

You took for /.

$url = explode('/', rtrim($url, '/'));
if (end($url) == 'low') {
    $url[count($url)-1] = 'high';
}
$url = implode('/', $url) .'/';
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement