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?