0

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,

4
  • what did you do for that so far? Commented Jun 13, 2018 at 10:00
  • I think you might find parse_url() helpful php.net/manual/en/function.parse-url.php Commented Jun 13, 2018 at 10:01
  • Is this URL your website address on which you're receiving requests or is it another site (e.g. for cURL requests)? Commented Jun 13, 2018 at 10:05
  • "I have this url" -- that is not an URL; an URL starts with a scheme (f.e. http) followed by a colon (:) and so on. F.e. http://www.website.com/download/long-file-name-123. Commented Jun 13, 2018 at 10:06

2 Answers 2

1
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"
Sign up to request clarification or add additional context in comments.

Comments

0
<?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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.