user9294038
user9294038

Reputation: 141

PHP: Replace first part of an url

I would like to change the first part of my url.

I have this url

www.website.com/download/long-file-name-123

I would like to change the "download" part to "downloads" like this.

www.website.com/downloads/long-file-name-123

The problem is that the url can also look like this:

www.website.com/download/files/file/long-file-name-123

So i need some way to always only change the first part of the url,

Upvotes: 0

Views: 727

Answers (2)

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

<?php
echo str_replace("download","downloads","www.website.com/download/long-file-name-123");
?>

For First occurrence of download

<?php
$urls = array("www.website.com/download/long-file-name-123","www.website.com/download/files/file/long-file-name-123");
$arrlength = count($urls);
for($x = 0; $x < $arrlength; $x++)
{
    $pos = strpos($urls[$x], "download");
    if ($pos !== false) {
        $newstring = substr_replace($urls[$x], "downloads", $pos, strlen("download"));
        echo ($newstring);
        echo ("\n");
    }
}
?> 

Output:

www.website.com/downloads/long-file-name-123
www.website.com/downloads/files/file/long-file-name-123

Live Demo:

http://tpcg.io/7tv7nF

Upvotes: 0

Damian Dziaduch
Damian Dziaduch

Reputation: 2127

php > $url = 'www.website.com/download/long-file-name-123';
php > $newUrl = str_replace('www.website.com/download', 'www.website.com/downloads', $url);
php > var_dump($newUrl);
string(44) "www.website.com/downloads/long-file-name-123"

Upvotes: 1

Related Questions