str_replace 和 preg_replace 在一台服务器上工作,但在另一台服务器上不起作用
更新:事实证明,以下问题是由我的生产服务器上的缓存问题引起的。感谢所有提供深思熟虑答案的人。
我在 php 页面上有一个简单的函数,它接受一个 url,例如:
http://myurl。 com/mypage.html?param1=value1
并将其转换为:
http:// myurl.com/searchpage.html?param1=value1
它所做的只是交换 page.html 部分。
为此,我使用以下代码:
$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);
上面的代码不是确切的代码,但是是一个很好的表示。它在一台服务器上运行得很好,但是当我推送到生产环境时,preg_replace 不起作用。我最初尝试使用str_replace。它也适用于我的本地开发计算机,但不适用于生产服务器。
我已确认 URL 变量输入正确。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这太令人费解了(抱歉地说)。为什么不只是:
That's horribly convoluted (sorry to say). Why not just:
为什么你不做
比使用正则表达式更好的方法呢?
Why don't you just do
Way better than using regexps.