简体   繁体   English

有关在URL中替换1个字符的更优雅解决方案的建议

[英]Suggestions for a more elegant solution to replacing 1 character in a URL

So, I have a URL I am receiving via an API. 因此,我有一个通过API接收的URL。 The pattern would be similar to https://www.example.co.uk/category/000000000k/0000 该模式类似于https://www.example.co.uk/category/000000000k/0000

I want to replace the second k character, with a x char. 我想用x字符替换第二个k字符。

I tried using str_replace() but it also replaces the first k character. 我尝试使用str_replace()但它也替换了第一个k字符。

So what I did was use preg_split() , so my solution is: 所以我要做的就是使用preg_split() ,所以我的解决方案是:

$url = preg_split( '/[\/]+/', 'https://www.example.co.uk/category/000000000k/0000' );
$url = $url[0] . '//' . $url[1] . '/' . $url[2] . '/' . str_replace( 'k', 'x', $url[3] ) . '/' . $url[4];

So, my solution works are long as the URL pattern does not change. 因此,只要URL模式不变,我的解决方案就可以正常工作。 However, I think it could be more elegant if my Regex was up to par. 但是,我认为,如果我的Regex达到标准,它可能会更优雅。

Anyone here could point me to a better path? 在座的任何人都可以指出我的更好路径吗?

If k/ always have numbers before that and another part doesn't have same pattern, this may work. 如果k/之前总是有数字,而另一部分没有相同的模式,则可能有效。

$url = "https://www.example.co.uk/category/000000000k/0000";
$url = preg_replace("/([0-9])k\//", "$1x/", $url);

Anoter pattern. 注记模式。 Find 3rd / , make sub string, and replace. 找到3rd / ,创建子字符串,然后替换。

$url = "https://www.example.co.uk/category/000000000k/0000";

$pos = 0;
for ($i = 0; $i < 3; $i++) {
    $pos = strpos($url, "/", $pos);
    if (FALSE === $pos) {
        // error
        break;
    }
    $pos++;
}

if ($pos) {
    $url_tmp = substr($url, $pos);
    $url_tmp = str_replace("k/", "x/", $url_tmp);
    $url = substr($url, 0, $pos).$url_tmp;
} else {
    // $pos is 0 or FALSE
    // error
}

If url source is not reliable, more checks may be needed. 如果url源不可靠,则可能需要进行更多检查。

$url = "https://www.example.co.uk/category/000000000k/0000";
echo preg_replace("/^[^k]+k[^k]+\Kk/", "x", $url),"\n";

Output: 输出:

https://www.example.co.uk/category/000000000x/0000

Explanation: 说明:

/               # regex delimiter
  ^             # beginning of line
    [^k]+       # 1 or more any character that is not k
    k           # 1rst letter k
    [^k]+       # 1 or more any character that is not k
    \K          # forget all we have seen until this position
    k           # 2nd letter k
/               # regex delimiter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM