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 = ' Her/Believe 100ml EDP-150x150.jpg';

and want output in this form

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

And with rawurlencode I received output like this:

I can get exactly what I want like this:

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

will result:

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.


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


$image = sprintf(
  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', 
                   implode('/', array_map('rawurlencode', explode('/', $info['path']))));