As a novice and beginner php learner, I'm using the Code-Canyon Premium URL Shortner script and done 2 days of research. Unfortunately I am unable to resolve my issue.
The url shorten script is urlencoding the API url that it sends to the script, In doing this it is replacing the & symbols with & causing the url to not work correctly on the final destination page.
I have tried to use preg_replace, str_replace and also tried to use urldecode on the destination page but none of these seem to work. Here is my current script:
$makeshort = "http://mywebsite.com/email/quote.php?quoteid=$visitor&customertype=fhbs";
$mkshrt = str_replace("/&/","%26",$makeshort);
$short = "http://shorturl.com/api?&api=REMOVED&format=text&url=".urlencode($mkshrt);
// Using Plain Text Response
$api_url = $short;
$res= #file_get_contents($api_url);
if($res)
$shorturl = $res;
$shorty = json_decode($shorturl);
$shorturl = $shorty->{'short'};
echo $shorturl;
Note: Where you see &format=text in the api url, I have tried to use it with and without the &format=text however this makes no difference what so ever.
I am hoping that there could be a simple and quick way to resolve this issue as I am only passing over 2 variables and its the second variable that is being displayed like this:
mywebsite.com/email/quote.php?quoteid=01234567890&customertype=fhbs
So the customertype variable is the one being messed up due to the amp; symbol.
I sincerely hope someone with the expertise could advise me on the best approach or even a simple way to resolve this issues as I really am at my whits end! MY knowledge is not good enough to research the exact key phrases in order to point myself in the right direction.
Thanks for your time in reading this and I hope someone would be kind enough to help me out here.
I know the feeling as i myself am just becoming to terms with coding and developing.
I personally would solve this by one of two ways, If you have tried to already use htmlspecialchars or htmlentities along with urldecode then the most simple and quickest way to achieve this would be to read the URL string then replace the &symbol with the & using str_replace and do either a meta refresh of the page or `header location redirect
Here is what i mean with a breif example however one must stress that some extra security maybe needed and this is ONLY a quick fix not a secure stable and permanent fix, Though one could play with this and maybe work something out for your own circumstances.
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(strstr($url, "&")){
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$url = str_replace('&', '&', $url);
echo "<meta http-equiv='refresh' content='0;URL=$url'>";
exit;
}
Alternative way with header location:
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(strstr($url, "&")){
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$url = str_replace('&', '&', $url);
header("Location: $url");
exit();
}
This will totally remove any & symbols from the url and replace them with &.
You can also play around with this to remove even more from the url string and replace things like / or forbidden words.
An example of the output will look like this:
Original url causing the problems:
http://mywebsite.com/email/quote.php?quoteid=1234567890&customertype=fhbs
New url after the script has executed and refreshed the page:
http://mywebsite.com/email/quote.php?quoteid=1234567890&customertype=fhbs
As you can see from the hyperlinked text above, The ampersand breaks the string and everything after that is not read correctly but when this script executes and refreshes the page the url will be just like the second hyperlink thus making the url work for what you require.
NOTE: THIS IS NOT A SECURE WAY OF DOING THINGS AND MAY NO BE IDEAL FOR YOUR CIRCUMSTANCES, THIS IS JUST AN IDEA AND HOPE THIS HELPS!
Thanks.
Related
This question already has answers here:
How to remove the querystring and get only the URL?
(16 answers)
Closed 3 years ago.
Is there a simple way to get the requested file or directory without the GET arguments? For example, if the URL is http://example.com/directory/file.php?paramater=value I would like to return just http://example.com/directory/file.php. I was surprised that there is not a simple index in $_SERVER[]. Did I miss one?
Edit: #T.Todua provided a newer answer to this question using parse_url.
(please upvote that answer so it can be more visible).
Edit2: Someone has been spamming and editing about extracting scheme, so I've added that at the bottom.
parse_url solution
The simplest solution would be:
echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH (everything before the first ?). As such, it is my new "best" solution to this problem.
strtok solution
Stackoverflow: How to remove the querystring and get only the url?
You can use strtok to get string before first occurence of ?
$url=strtok($_SERVER["REQUEST_URI"],'?');
Performance Note:
This problem can also be solved using explode.
Explode tends to perform better for cases splitting the sring only on a single delimiter.
Strtok tends to perform better for cases utilizing multiple delimiters.
This application of strtok to return everything in a string before the first instance of a character will perform better than any other method in PHP, though WILL leave the querystring in memory.
An aside about Scheme (http/https) and $_SERVER vars
While OP did not ask about it, I suppose it is worth mentioning:
parse_url should be used to extract any specific component from the url, please see the documentation for that function:
parse_url($actual_link, PHP_URL_SCHEME);
Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVER variables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:
https://stackoverflow.com/a/6768831/1589379
It is important to note that these $_SERVER variables are populated at runtime, by whichever engine is doing the execution (/var/run/php/ or /etc/php/[version]/fpm/). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI (because it's required by php), and those listed in RFC 3875 (see: PHP: $_SERVER ) because they are required of webservers.
please note: spaming links to your answers across other questions is not in good taste.
You can use $_SERVER['REQUEST_URI'] to get requested path. Then, you'll need to remove the parameters...
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
Then, add in the hostname and protocol.
echo 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
You'll have to detect protocol as well, if you mix http: and https://. That I leave as an exercise for you. $_SERVER['REQUEST_SCHEME'] returns the protocol.
Putting it all together:
echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST']
. explode('?', $_SERVER['REQUEST_URI'], 2)[0];
...returns, for example:
http://example.com/directory/file.php
php.com Documentation:
$_SERVER — Server and execution environment information
explode — Split a string by a string
parse_url — Parse a URL and return its components (possibly a better solution)
Solution:
echoparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Here is a solution that takes into account different ports and https:
$pageURL = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
if ($_SERVER['SERVER_PORT'] != '80')
$pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF'];
else
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Or a more basic solution that does not take other ports into account:
$pageURL = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
I actually think that's not the good way to parse it. It's not clean or it's a bit out of subject ...
Explode is heavy
Session is heavy
PHP_SELF doesn't handle URLRewriting
I'd do something like ...
if ($pos_get = strpos($app_uri, '?')) $app_uri = substr($app_uri, 0, $pos_get);
This detects whether there's an actual '?' (GET standard format)
If it's ok, that cuts our variable before the '?' which's reserved for getting datas
Considering $app_uri as the URI/URL of my website.
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;
You can use $_GET for url params, or $_POST for post params, but the $_REQUEST contains the parameters from $_GET $_POST and $_COOKIE, if you want to hide the URI parameter from the user you can convert it to a session variable like so:
<?php
session_start();
if (isset($_REQUEST['param']) && !isset($_SESSION['param'])) {
// Store all parameters received
$_SESSION['param'] = $_REQUEST['param'];
// Redirect without URI parameters
header('Location: /file.php');
exit;
}
?>
<html>
<body>
<?php
echo $_SESSION['param'];
?>
</body>
</html>
EDIT
use $_SERVER['PHP_SELF'] to get the current file name or $_SERVER['REQUEST_URI'] to get the requested URI
Not everyone will find it simple, but I believe this to be the best way to go around it:
preg_match('/^[^\?]+/', $_SERVER['REQUEST_URI'], $return);
$url = 'http' . ('on' === $_SERVER['HTTPS'] ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $return[0]
What is does is simply to go through the REQUEST_URI from the beginning of the string, then stop when it hits a "?" (which really, only should happen when you get to parameters).
Then you create the url and save it to $url:
When creating the $url... What we're doing is simply writing "http" then checking if https is being used, if it is, we also write "s", then we concatenate "://", concatenate the HTTP_HOST (the server, fx: "stackoverflow.com"), and concatenate the $return, which we found before, to that (it's an array, but we only want the first index in it... There can only ever be one index, since we're checking from the beginning of the string in the regex.).
I hope someone can use this...
PS. This has been confirmed to work while using SLIM to reroute the URL.
I know this is an old post but I am having the same problem and I solved it this way
$current_request = preg_replace("/\?.*$/","",$_SERVER["REQUEST_URI"]);
Or equivalently
$current_request = preg_replace("/\?.*/D","",$_SERVER["REQUEST_URI"]);
It's shocking how many of these upvoted/accepted answers are incomplete, so they don't answer the OP's question, after 7 years!
If you are on a page with URL like: http://example.com/directory/file.php?paramater=value
...and you would like to return just: http://example.com/directory/file.php
then use:
echo $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Why so complicated? =)
$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];
this should really do it man ;)
I had the same problem when I wanted a link back to homepage. I tried this and it worked:
<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">
Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)
The problem i'm facing right now is im getting a URL, like so:
www.example.com/example.php?url=www.google.com
now the problem is, if theres a get in my url, like so:
www.example.com/example.php?url=www.google.com?id=1
it doesn't actually cause a problem yet, but if theres two GET vars in the my URL, it doesn't know where the "and" goes, the first get or the second one, and basically just chooses the first, ex:
www.example.com/example.php?url=www.google.com?id=1&username=me
is there a workaround? I could recode a lot of things to have it as one get variable, but it'll involve a lot of work and I wish i could have a solution!
thanks!
Heres my code:
$facebookapi=new facebook(array('appId'=>'*******','secret'=>'********','fileUpload'=>'false'));
$url='http://******.com/questions/view.php?id=884&username=robot';
$facebookapi->api('/me/******app:answer?question=' . urlencode($url),'POST');
You need urlencode to encode the url parameter.
$url = 'www.google.com?id=1';
echo 'www.example.com/example.php?url='.urlencode($url).'&username=me';
Edit:
After seeing your posted code, it seems that you should use the third parameter for params.
$url='http://******.com/questions/view.php?id=884&username=robot';
$facebookapi->api('/me/******app:answer', 'POST', array('question' => $url));
Well the function urlencode is perfect for this.
Once the url is encoded,
The first get variable will turn from this
www.google.com?id=1&username=me
to this
www.google.com%3Fid%3D1&6username=me
Your website will then appear as [www.example.com/example.php?url=www.google.com%3Fid%3D1%26username%3Dme]
Once PHP receives that variable you can decode it
$url = urldecode($_GET['url']);
Note: some versions of PHP do it automatically.
This question already has answers here:
How to remove the querystring and get only the URL?
(16 answers)
Closed 3 years ago.
Is there a simple way to get the requested file or directory without the GET arguments? For example, if the URL is http://example.com/directory/file.php?paramater=value I would like to return just http://example.com/directory/file.php. I was surprised that there is not a simple index in $_SERVER[]. Did I miss one?
Edit: #T.Todua provided a newer answer to this question using parse_url.
(please upvote that answer so it can be more visible).
Edit2: Someone has been spamming and editing about extracting scheme, so I've added that at the bottom.
parse_url solution
The simplest solution would be:
echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH (everything before the first ?). As such, it is my new "best" solution to this problem.
strtok solution
Stackoverflow: How to remove the querystring and get only the url?
You can use strtok to get string before first occurence of ?
$url=strtok($_SERVER["REQUEST_URI"],'?');
Performance Note:
This problem can also be solved using explode.
Explode tends to perform better for cases splitting the sring only on a single delimiter.
Strtok tends to perform better for cases utilizing multiple delimiters.
This application of strtok to return everything in a string before the first instance of a character will perform better than any other method in PHP, though WILL leave the querystring in memory.
An aside about Scheme (http/https) and $_SERVER vars
While OP did not ask about it, I suppose it is worth mentioning:
parse_url should be used to extract any specific component from the url, please see the documentation for that function:
parse_url($actual_link, PHP_URL_SCHEME);
Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVER variables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:
https://stackoverflow.com/a/6768831/1589379
It is important to note that these $_SERVER variables are populated at runtime, by whichever engine is doing the execution (/var/run/php/ or /etc/php/[version]/fpm/). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI (because it's required by php), and those listed in RFC 3875 (see: PHP: $_SERVER ) because they are required of webservers.
please note: spaming links to your answers across other questions is not in good taste.
You can use $_SERVER['REQUEST_URI'] to get requested path. Then, you'll need to remove the parameters...
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
Then, add in the hostname and protocol.
echo 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
You'll have to detect protocol as well, if you mix http: and https://. That I leave as an exercise for you. $_SERVER['REQUEST_SCHEME'] returns the protocol.
Putting it all together:
echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST']
. explode('?', $_SERVER['REQUEST_URI'], 2)[0];
...returns, for example:
http://example.com/directory/file.php
php.com Documentation:
$_SERVER — Server and execution environment information
explode — Split a string by a string
parse_url — Parse a URL and return its components (possibly a better solution)
Solution:
echoparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Here is a solution that takes into account different ports and https:
$pageURL = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
if ($_SERVER['SERVER_PORT'] != '80')
$pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF'];
else
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Or a more basic solution that does not take other ports into account:
$pageURL = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
I actually think that's not the good way to parse it. It's not clean or it's a bit out of subject ...
Explode is heavy
Session is heavy
PHP_SELF doesn't handle URLRewriting
I'd do something like ...
if ($pos_get = strpos($app_uri, '?')) $app_uri = substr($app_uri, 0, $pos_get);
This detects whether there's an actual '?' (GET standard format)
If it's ok, that cuts our variable before the '?' which's reserved for getting datas
Considering $app_uri as the URI/URL of my website.
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;
You can use $_GET for url params, or $_POST for post params, but the $_REQUEST contains the parameters from $_GET $_POST and $_COOKIE, if you want to hide the URI parameter from the user you can convert it to a session variable like so:
<?php
session_start();
if (isset($_REQUEST['param']) && !isset($_SESSION['param'])) {
// Store all parameters received
$_SESSION['param'] = $_REQUEST['param'];
// Redirect without URI parameters
header('Location: /file.php');
exit;
}
?>
<html>
<body>
<?php
echo $_SESSION['param'];
?>
</body>
</html>
EDIT
use $_SERVER['PHP_SELF'] to get the current file name or $_SERVER['REQUEST_URI'] to get the requested URI
Not everyone will find it simple, but I believe this to be the best way to go around it:
preg_match('/^[^\?]+/', $_SERVER['REQUEST_URI'], $return);
$url = 'http' . ('on' === $_SERVER['HTTPS'] ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $return[0]
What is does is simply to go through the REQUEST_URI from the beginning of the string, then stop when it hits a "?" (which really, only should happen when you get to parameters).
Then you create the url and save it to $url:
When creating the $url... What we're doing is simply writing "http" then checking if https is being used, if it is, we also write "s", then we concatenate "://", concatenate the HTTP_HOST (the server, fx: "stackoverflow.com"), and concatenate the $return, which we found before, to that (it's an array, but we only want the first index in it... There can only ever be one index, since we're checking from the beginning of the string in the regex.).
I hope someone can use this...
PS. This has been confirmed to work while using SLIM to reroute the URL.
I know this is an old post but I am having the same problem and I solved it this way
$current_request = preg_replace("/\?.*$/","",$_SERVER["REQUEST_URI"]);
Or equivalently
$current_request = preg_replace("/\?.*/D","",$_SERVER["REQUEST_URI"]);
It's shocking how many of these upvoted/accepted answers are incomplete, so they don't answer the OP's question, after 7 years!
If you are on a page with URL like: http://example.com/directory/file.php?paramater=value
...and you would like to return just: http://example.com/directory/file.php
then use:
echo $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
Why so complicated? =)
$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];
this should really do it man ;)
I had the same problem when I wanted a link back to homepage. I tried this and it worked:
<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">
Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)
I know that I should encodeURI any url passed to anything else, because I read this:
http://www.digitalbart.com/jquery-and-urlencode/
I want to share the current time of the current track I am listening to.
So I installed the excellent yoururls shortener.
And I have a bit of code that puts all the bits together, and makes the following:
track=2&time=967
As I don't want everyone seeing my private key, I have a little php file which takes the input, and appends the following, so it looks like this:
http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=http://urltoshorten?track=2&time=967
So in the main page, I call the jquery of $("div.shorturl").load(loadall);
It then does a little bit of CURL and then shortener returns a nice short URL.
Like this:
$myurl='http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=' . $theurl;
$ch = curl_init($myurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
echo $data;
All perfect.
Except... the URL which is shortened is always in the form of http://urltoshorten?track=2 - anything after the ampersand is shortened.
I have tried wrapping the whole URL in php's URLencode, I've wrapped the track=2&time=967 in both encodeURI and encodeURIComponent, I've evem tried wrapping the whole thing in one or both.
And still, the & breaks it, even though I can see the submitted url looks like track=1%26time%3D5 at the end.
If I paste this or even the "plain" version with the unencoded url either into the yoururls interface, or submit it to the yoururls via the api as a normal URL pasted into the location bar of the browser, again it works perfectly.
So it's not yoururls at fault, it seems like the url is being encoded properly, the only thing I can think of is CURL possibly?
Now at this point you might be thinking "why not replace the & with a * and then convert it back again?".
OK, so when the url is expanded, I get the values from
var track = $.getUrlVar('track');
var time = $.getUrlVar('time');
so I COULD lose the time var, then do a bit of finding on where the * is in track and then assume the rest of anything after * is the time, but it's a bit ugly, and more to the point, it's not really the correct way to do things.
If anyone could help me, it would be appreciated.
I have tried wrapping the whole URL in php's URLencode
That is indeed what you have to do (assuming by ‘URL’ you mean inner URL being passed as a component of the outer URL). Any time you put a value in a URL component, you need to URL-encode, whether the value you're setting is a URL or not.
$myurl='http://...?...&url='.rawurlencode($theurl);
(urlencode() is OK for query parameters like this, but rawurlencode() is also OK for path parts, so unless you really need spaces to look slightly prettier [+ vs %20], I'd go for rawurlencode() by default.)
This will give you a final URL like:
http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=http%3A%2F%2Furltoshorten%3Ftrack%3D2%26time%3D967
Which you should be able to verify works. If it doesn't, there is something wrong with yourls-api.php.
I have tried wrapping the whole URL in php's URLencode, I've wrapped the track=2&time=967 in both encodeURI and encodeURIComponent, I've evem tried wrapping the whole thing in one or both. And still, the & breaks it, even though I can see the submitted url looks like track=1%26time%3D5 at the end.
Maybe an explanation of how HTTP variables work will help you out.
If I'm getting a page with the following variables and values:
var1 = Bruce Oxford
var2 = Brandy&Wine
var3 = ➋➌➔ (unicode chars)
We uri-encode the var name and the value of the var, ie:
var1 = Bruce+Oxford
var2 = Brandy%26Wine
var3 = %E2%9E%8B%E2%9E%8C%E2%9E%94
What we are not doing is encoding the delimiting charecters, so what the request data will look like for the above is:
?var1=Bruce+Oxford&var2=Brandy%26Wine&var3=%E2%9E%8B%E2%9E%8C%E2%9E%94
Rather than:
%3Fvar1%3DBruce+Oxford%26var2%3DBrandy%26Wine%26var3%3D%E2%9E%8B%E2%9E%8C%E2%9E%94
Which is of course just gibberish.
UPDATE: As it turns out, the below is caused by a caching issue on my production server. Thanks to everybody who contributed thoughtful answers.
I have a simple function on a php page that takes a url such as:
http://myurl.com/mypage.html?param1=value1
and converts it to:
http://myurl.com/searchpage.html?param1=value1
All it does it swap out the page.html portion.
To do this, I use the following:
$currentUrl = $this->getCurrentUrl(); // Grabs the current url, i.e 'http://myurl.com/mypage.html?param1=value1'
// Derive a search pattern from the current url
$pattern = "/" . str_replace(array("/", ".", "-"), array("\\/", "\\.", "\\-"), $currentUrl) . "/";
// get rid of the 'mypage.html'
$newUrl = preg_replace($pattern, 'http://myurl.com/', $currentUrl);
// replace the question mark with the correct page
$newUrl = str_replace("/?", "/searchpage.html?", $newUrl);
The above code is not the exact code but is a good representation. It works beautifully on one server, but when I push to production, the preg_replace does not work. I originally attempted to use str_replace. It also works on my local development machine, but not on the production server.
I have confirmed that the URL variables are coming in correctly. Any ideas?
That's horribly convoluted (sorry to say). Why not just:
$newUrl = preg_replace('!\bmypage\.html\b!', 'searchpage.html', $oldUrl);
Why don't you just do
$pieces = explode('/',$url);
str_replace('mypage','searchpage',$pieces[2]);
$newURL = implode('/',$pieces);
Way better than using regexps.