views:

190

answers:

2

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?

+2  A: 

That's horribly convoluted (sorry to say). Why not just:

$newUrl = preg_replace('!\bmypage\.html\b!', 'searchpage.html', $oldUrl);
cletus
The horrible code is because I am testing from a few angles. What you are seeing is the result of a desperate attempt to get it to work. The code you propose is much cleaner - the trouble is that I don't know what "mypage.html" will be. I suppose I could explode the original URL to derive that.
retailevolved
@retailevolved perhaps you should post what your actual problem is. Also you can use `parse_url()` to easily get the path from the URL.
cletus
I have posted in great detail what my issue is. I thank you for your contribution. I tested it on my local server and it works great. On production, it's a no go.
retailevolved
A: 

Why don't you just do

$pieces = explode('/',$url);
str_replace('mypage','searchpage',$pieces[2]);
$newURL = implode('/',$pieces);

Way better than using regexps.

Ben
This also works great on my test machine but not on production. It's becoming clear to me that this isn't an issue with str_replace / preg_replace usage but more likely an environment issue...
retailevolved
Can't you "emulate" the test machine environment on the production one?
Ben