str_replace 和 preg_replace 在一台服务器上工作,但在另一台服务器上不起作用

发布于 2024-08-27 02:24:27 字数 1085 浏览 2 评论 0原文

更新:事实证明,以下问题是由我的生产服务器上的缓存问题引起的。感谢所有提供深思熟虑答案的人。

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

会发光的星星闪亮亮i 2024-09-03 02:24:27

这太令人费解了(抱歉地说)。为什么不只是:

$newUrl = preg_replace('!\bmypage\.html\b!', 'searchpage.html', $oldUrl);

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

$newUrl = preg_replace('!\bmypage\.html\b!', 'searchpage.html', $oldUrl);
药祭#氼 2024-09-03 02:24:27

为什么你不做

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

比使用正则表达式更好的方法呢?

Why don't you just do

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

Way better than using regexps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文