php 如何将“+”加号替换为其对应的“%2B”网址编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4763917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:17:24  来源:igfitidea点击:

How can I replace the "+" plus sign with its corresponding url encoding of "%2B"?

phpstring

提问by Ronedog

I'm having some trouble replacing the "+" sign with its urlencoded string of "%2B". How can I do this?

我在用“%2B”的 urlencoded 字符串替换“+”号时遇到了一些麻烦。我怎样才能做到这一点?

This is what I've tried:

这是我尝试过的:

Text Entered into text box:

在文本框中输入的文本:

plus(+)

I then urlencode the string:

然后我对字符串进行 urlencode:

$string = urlencode($string);

String now looks like:

字符串现在看起来像:

plus%28+%29

I want to have the "+" urlencoded, or else when I urldecode() the data to display in browser I end up with:

我想对“+”进行 urlencoded,否则当我 urldecode() 要在浏览器中显示的数据时,我最终会得到:

plus( ) 

because urldecode() interprets the "+" to be a space.

因为 urldecode() 将“+”解释为空格。

I tried using php's str_replace() but I keep getting a "NULL" returned as the value for "$new_string":

我尝试使用 php 的 str_replace() 但我不断得到一个“NULL”作为“$new_string”的值返回:

$new_string = str_replace('+', '%2B', $string);

Any ideas?

有任何想法吗?

Thanks in advance!

提前致谢!

回答by John Kugelman

That is strange. When I use urlencodeon plus(+)I get plus%28%2B%29. Make sure you're using it correctly.

这很奇怪。当我使用urlencodeonplus(+)我得到plus%28%2B%29. 确保您正确使用它。

You might also try rawurlencode. It will encode spaces as %20instead of +.

你也可以试试rawurlencode。它将编码空格%20而不是+.

回答by Norman Huth

That helped me:

这对我有帮助:

function _rawurlencode($string) {
    $string = rawurlencode(str_replace('+','%2B',$string));
    return $string;
}