在PHP中用%20替换空格。urlencode和rawurlencode不起作用

jef*_*eff 0 php whitespace urlencode url-encoding rawurl

我正在尝试由多字字符串构成一个URL:

$str = "my string"
Run Code Online (Sandbox Code Playgroud)

而我试图得到:

"http mysite.com/search/my%20string"
Run Code Online (Sandbox Code Playgroud)

但我无法使用PHP做到这一点。

urlencode($str) => "my+string"
rawurlencode($str)=>"my string"
Run Code Online (Sandbox Code Playgroud)

我怎么能得到"my%20string"

谢谢你的帮助 !

PS:

也许我可以做,str_replace(urlencode(),etc); 但是urlencode是否有一个参数,这样它本身就可以正确转换?

PS 2:

事实证明,正如Amal Murali所说的那样,rawurlencode()确实如此,当我将鼠标悬停在链接上时,在浏览器中看不到它。

但是,当我检查源代码或单击链接时,会看到rawurlencode();生成正确的链接。(带有%20。)。

Ama*_*ali 6

rawurlencode()是您要寻找的。但是,如果您Content-Type将设置为text/html(这是默认设置),那么您将看到空格字符而不是编码的实体。

header('Content-Type: text/plain');
$str = "my string";
echo rawurlencode($str); // => my%20string
Run Code Online (Sandbox Code Playgroud)

注意:我不建议您更改Content-Type原始脚本中的标题。只是为了表明您的rawurlencode()呼叫正在正常工作,并说明为什么看不到它。