开发者

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 w开发者_如何转开发rap 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


how about str_replace?

<?php
$newurl = str_replace('low', 'high', $oldurl);
?>

documentation; http://php.net/manual/en/function.str-replace.php

edit; Rik is right; if your domain (or any other part of the url for that matter) includes the string "low", this will mess up your link. So: if your url may contain multiple 'low' 's, you will have to add an extra indicator in the script. An example of that would be including the /'s in your str_replace.


You took \ for /.

$url = explode('/', rtrim($url, '/'));
if (end($url) == 'low') {
    $url[count($url)-1] = 'high';
}
$url = implode('/', $url) .'/';


Use parse_url to split the URL into its components, modify them as required (here you can use explode to split the path into its segments), and then rebuild the URL with http_build_url.


<?php

class TestURL extends PHPUnit_Framework_TestCase {
    public function testURL() {
        $URL =  'http://www.mydomain.com/article/paragraph/low/';
        $explode = explode('/', $URL);
        $explode[5] = 'high';
        $expected = 'http://www.mydomain.com/article/paragraph/high/';
        $actual = implode('/', $explode);
        $this->assertEquals($expected, $actual);
    }
}

--

phpunit simple-test.php 
PHPUnit 3.4.13 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 4.75Mb

OK (1 test, 1 assertion)


This will probably be enough:

$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = str_replace('/low/', '/high/', $url);

or with regular expressions (it allows more flexibility)

$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = preg_replace('/low(\/?)$/', 'high$1', $url);

Note that the string approach will replace any low segment and only if it's followed by a /. The regex approach will replace low only if it's the last segment and it may not be followed by a /.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜