Yegya Yegya - 8 days ago 4
PHP Question

How to convert this url to %20?

A very simple problem which might have been solved here a lot of time, but I'm not getting what I want.

I have an image url like this:

$image = 'http://perfumepalace.arctechsolution.com/image/cache/data/another/For Her/Believe 100ml EDP-150x150.jpg';


and want output in this form

http://perfumepalace.arctechsolution.com/image/cache/data/another/For%20Her/Believe%20100ml%20EDP-150x150.jpg


Yes ofcourse you will tell me I can use urlencode or rawurlencode. Believe me I've tried and still no luck.

With urlencode I get like this

http%3A%2F%2Fperfumepalace.arctechsolution.com%2Fimage%2Fcache%2Fdata%2Fanother%2FFor+Her%2FBelieve+100ml+EDP-150x150.jpg


And with rawurlencode I received output like this:

http%3A%2F%2Fperfumepalace.arctechsolution.com%2Fimage%2Fcache%2Fdata%2Fanother%2FFor%20Her%2FBelieve%20100ml%20EDP-150x150.jpg


With
str_replace
I can get exactly what I want like this:

str_replace('+', '%20', $image);


will result:
http://perfumepalace.arctechsolution.com/image/cache/data/another/For%20Her/Believe%20100ml%20EDP-150x150.jpg


but I want to get them using urlencode or rawurlencode. But these functions encode even slash / part as well.

Is there any way to url encode only spaces in the url?

Edit: Yes i can use basename() or pathinfo to encode only part of the url. But the directory name might also contain the space character, so converting only filename is also not a possibility here.

And actually I want to know if we can use urlencode, or rawurlencode in full url without affecting the '/' of the fullurl. I don't want the regex suggestions eigher.

Note: The complication part is that 'For Her' directory section in the url path, and the level of directory is also not fixed.

Answer

What you need is rawurlencode(), but only encode the necessary part of your url.

Example:

$image = sprintf(
  'http://perfumepalace.arctechsolution.com/image/cache/data/another/%s/%s',
  rawurlencode('For Her'),
  rawurlencode('Believe 100ml EDP-150x150.jpg')
);

But if you still want to apply to the whole url string, you could do like below:

function my_url_encode($url) {
    $info = parse_url($url);
    return sprintf('%s://%s/%s', 
                   $info['scheme'], 
                   $info['host'], 
                   implode('/', array_map('rawurlencode', explode('/', $info['path']))));
}