PHP 将 URL 段替换为 str_replace();

PHP replace URL segment with str_replace();

我的域名后面有 "/foo/bar/url/"

我想要的是在我的字符串中找到倒数第二个斜杠符号并将其替换为斜杠符号 + 主题标签。像这样:从//#(问题不在于如何得到URL,而是如何处理它)

这是如何实现的?做这样的事情的最佳做法是什么? 目前我很确定我应该使用 str_replace();

更新。我认为 preg_replace() 适合我的情况。但是还有另一个问题:正则表达式应该是什么样子才能解决我的问题?

P.S。以防万一,我正在使用 SilverStripe 框架 (v3.1.12)

这是一个可行的方法。可能有更清洁的方法。

// Let's assume you already have $url_string populated
$url_string = "http://whatever.com/foo/bar/url/";

$url_explode = explode("\",$url_string);
$portion_count = count($url_explode);

$affected_portion = $portion_count - 2; // Minus two because array index starts at 0 and also we want the second to last occurence

$i = 0;
$output = "";
foreach ($url_explode as $portion){

    $output.=$portion;

    if ($i == $affected_portion){
        $output.= "#";
    }

    $i++;

}

$new_url = $output;
$url = '/foo/bar/url/';

if (false !== $last = strrpos($url, '/')) {
    if (false !== $penultimate = strrpos($url, '/', $last - strlen($url) - 1)) {
        $url = substr_replace($url, '/#', $penultimate, 1);
    }
}

echo $url;

这将输出

/foo/bar/#url/

如果要去掉最后一个/:

echo rtrim($url, '/'); // print /foo/bar/#url

就我而言,这解决了我的问题:

$url = $this->Link();
$url = rtrim($url, '/');
$url = substr_replace($url, '#', strrpos($url, '/') + 1, 0);

假设你现在有

$url = $this->Link(); // e.g. /foo/bar/my-urlsegment

你可以这样组合

$handledUrl = $this->ParentID 
    ? $this->Parent()->Link() + '#' + $this->URLSegment
    : $this->Link();

其中 $this->Parent()->Link() 例如/foo/bar 并且 $this->URLSegmentmy-urlsegment

$this->ParentID 还会检查我们是否有父页面或是否在 SiteTree 的顶层

我可能来不及回答这个问题了,但我认为这可能对您有所帮助。您可以像

一样简单地使用 preg_replace
$url = '/foo/bar/url/';
echo preg_replace('~(\/)(\w+)\/$~',"#",$url);

输出:

/foo/bar/#url