如何对字符串进行 URL 编码

发布于 2024-11-08 14:00:45 字数 536 浏览 0 评论 0原文

$flr = preg_replace("/\\\'/","%27",$flr);

如果 URL 具有此符号:',则它会被 %27 替换,并且 URL 应变为 http://localhost/%27,但是这个不起作用。

例如:

$flr = preg_replace("/\\\"/","%22",$flr);

URL 替换有效,我得到 http://localhost/%22

但是为什么我的第一个示例不起作用?

为了测试,我正在使用:

function isValidFLR(&$flr) {
    $flr = preg_replace("/\\\'/","%27",$flr);
    $flr = preg_replace("/\\\"/","%22",$flr);
    echo $flr;
    die();
}
$flr = preg_replace("/\\\'/","%27",$flr);

If URL has this symbol: ' it got replaced by %27 and the URL should become http://localhost/%27, but this doesn't work.

For example:

$flr = preg_replace("/\\\"/","%22",$flr);

URL replacement works and I get http://localhost/%22

But then why doesn't my first example work?

To test, I'm using:

function isValidFLR(&$flr) {
    $flr = preg_replace("/\\\'/","%27",$flr);
    $flr = preg_replace("/\\\"/","%22",$flr);
    echo $flr;
    die();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

残月升风 2024-11-15 14:00:45

您所要求的只是 urlencode() ?

如果您只想替换几个特定字符,您也许应该尝试使用 str_replace()

Is what you asking for simply urlencode() ?

If you just want to replace a couple of certain characters, you should perhaps try using str_replace() instead.

梦在深巷 2024-11-15 14:00:45
$flr = preg_replace("/'/","%27",$flr);

会起作用的。

但是,正如其他人所说,执行此操作的 PHP 函数之一可能是更好的解决方案。

$flr = preg_replace("/'/","%27",$flr);

will work.

But, as others have said, one of the PHP functions which does this could be a better solution.

岁月染过的梦 2024-11-15 14:00:45

您遇到了 PHP 的字符串引号转义问题,与正则表达式的转义混合在一起。你可能会得到一个非常混乱的反斜杠序列!

解决您的问题的最直接的解决方案就是在搜索双引号时在正则表达式字符串上使用单引号:

$flr = preg_replace('/\\\"/',"%22",$flr);

但是,在您的情况下,一个更简单的解决方案正在乞求:为什么您需要使用正则表达式在这种情况下?一个简单的 str_replace() 也可以完成这项工作,并且可以避免所有那些令人毛骨悚然的斜线。

You're having problems with PHP's string escaping of quotes, getting mixed in with regex's escaping. You could end up with a very messy sequence of backslashes!

The most direct solution for your problem is simply to use single quotes on your regex string when you're searching for double-quotes:

$flr = preg_replace('/\\\"/',"%22",$flr);

However, in your case, an even simpler solution is going begging: Why do you need to use regex at all in this case? A simple str_replace() would do this job just as well, and would avoid all those hair-raising slashes.

梦里寻她 2024-11-15 14:00:45

如何测试以下内容:(

$flr = preg_replace("/\\\"/","%27",$flr);

' 替换为 "

What about to test with following :

$flr = preg_replace("/\\\"/","%27",$flr);

(replace ' to ")

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