So, I have a URL I am receiving via an API. The pattern would be similar to https://www.example.co.uk/category/000000000k/0000
I want to replace the second k
character, with a x
char.
I tried using str_replace()
but it also replaces the first k
character.
So what I did was use preg_split()
, so my solution is:
$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. However, I think it could be more elegant if my Regex was up to par.
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.
$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.
$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 = "https://www.example.co.uk/category/000000000k/0000";
echo preg_replace("/^[^k]+k[^k]+\Kk/", "x", $url),"
";
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