4

I have an url with spaces:

http://mihalko.eu/image/data/ister/Nomad Plus-G- cierno cervena.jpg

(browser can open this link) What is the best way to urlencode this url (space=%20)?

Nomad%20Plus-G-%20cierno%20cervena.jpg

urlencode:

http%3A%2F%2Fmihalko.eu%2Fimage%2Fdata%2Fister%2FNomad+Plus-G-+cierno+cervena.jpg

(browser can't open this link)
urlencode give me this result, but my browser wont't open this url.

1
  • 4
    That's URL encoding, not HTML. Commented Jun 7, 2012 at 17:02

3 Answers 3

2

Use rawurlencode:

echo rawurlencode('Nomad Plus-G- cierno cervena.jpg');
// Nomad%20Plus-G-%20cierno%20cervena.jpg

If you're okay with spaces being encoded as + then just use urlencode instead.

Sign up to request clarification or add additional context in comments.

3 Comments

I edited my question, but the result is same with rawurlencode. But why?
@Adrian You shouldn't encode the whole url, only the components that need encoding individually. You don't want to encode all the /s in your url, but if you wanted a / in a component you would encode it.
Unfortunately I have some directories with space in their names, and this trick doesn't work. Please check my comment below.
0

You could search for the last "/" and use urlencode for last part of your string, like that:

$pos=strrpos($url,"/")+1;
$newurl=substr($url,0,$pos) . rawurlencode(substr($url,$pos));

If your only problems are spaces, then you could use

str_replace(" ","%20",$url);

1 Comment

Thank you, this works until I have space in the directory name: d.pr/n/uRFH+ (code with comment)
0

str_replace('%2F','/',rawurlencode('url')); This is working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.