Domanda

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.).

È stato utile?

Soluzione

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.

Altri suggerimenti

// Set URL Base so you can add to it.
$url = "httpmysite.com/search/";
// Set String to search for.
$x = " ";
// Set string to replace with. 
$y = "%20";
//Set string to search.
$z = "my site";
// Concatenate
$url = $url . str_replace($x,$y,$z);

I layed it out that way to present each step, but I'd just write a method / function for it.

Actually, given that it is standard now to use "_" or "-" in place of spaces for SEO purposes, I'd just replace %20 with _ or -

Let me know if that helps.

If you want to see %20 in your URLs you must use rawurlencode().

You should not mess with the content type, because you risk seeing some browsers getting confused and serving your HTML pages as text (as source), that is with the tags not being interpreted into a proper web page.

Of course if you want to debug your PHP code by outputting the %20, you are not going to really see a visible result as the text/html encoding will tell your browser to interpret the codes and thus your %20 will transparently be converted into a space.

The "use plain/text" suggestion is just for debugging purposes so you can really see the %20 being generated. You will use it to create URLs anyway, so the whole plain vs html encoding won't apply to you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top