Q:

URL Replacement in PHP

I'm trying to change a value in a string that's holding my current URL. I'm trying to get something like
http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory

to look like 
http://myurl.com/test/end.php?req=&srclang=english&destlang=english&service=MyMemory

replacing begin.php for end.php.
I need the end.php to be stored in a variable so it can change, but begin.php can be a static string.
I tried this, but it didn't work:
$endURL   = 'end.php';
$beginURL = 'begin.php';
$newURL   = str_ireplace($beginURL,$endURL,$url);

EDIT:
Also, if I wanted to replace
http://myurl.com/begin.php?req=&srclang=english&destlang=english&service=MyMemory

with
http://newsite.com/end.php?req=&srclang=english&destlang=english&service=MyMemory

then how would I go about doing that?

A:

Assuming that you want to replace the script filename of the url, you can use something like this :
<?php 
  $endURL   = 'end.php';
  $url ="http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory";
  $pattern = '/(.+)\/([^?\/]+)\?(.+)/';
  $replacement = '${1}/'.$endURL.'?${3}';
  $newURL = preg_replace($pattern , $replacement, $url);

   echo "url : $url <br>";
   echo "newURL : $newURL <br>";
?>

