Search code examples
phpwhitespaceurlencodeurl-encodingrawurl

Substituting whitespaces with %20 in PHP. urlencode and rawurlencode does not work


I'm trying to constitute a URL from a multi-word string: so I have

$str = "my string"

and I 'm trying to get :

"http mysite.com/search/my%20string"

but I could not do it with PHP.

urlencode($str) => "my+string"
rawurlencode($str)=>"my string"

how can I get "my%20string" ?

Thanks for any help !

P.S.:

Maybe I can do str_replace(urlencode(),etc); but is there an argument for urlencode so that it converts correctly by itself?

P.S. 2:

Turns out that, as Amal Murali said, rawurlencode() WAS doing it, I just didn't see it on the browser, when I hover on the link with my mouse.

But when I check the source code, or click on the link, I see that rawurlencode(); produces the correct link. (With %20's.).


Solution

  • rawurlencode() is what you're looking for. However, if your Content-Type is set to text/html (which is the default), then you will see the space character instead of the encoded entity.

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

    Note: I'm not suggesting that you should change the Content-Type header in your original script. It's just to show that your rawurlencode() call is working and to explain why you're not seeing it.