PHP:fopen(UrlWithWhiteSpaces)

As you can see on the title, I am trying to fopen() a Url with whitespaces. Other stackoverflow posts didn't help really, could it possibly be that they are outdated?
I have tried:

  • urlencode
  • rawurlencode

None of the above works , http://test.com/two - words.jpg this gives me:

  • urlencode: http%3A%2F%2Ftest.com%2Ftwo+-+words.jpg
  • rawurlencode: http%3A%2F%2Ftest.com%2Ftwo%20-%20words.jpg

When i am trying to clearly get http://test.com/two%20-%20words.jpg , which is what the browser shows when you type http://test.com/two - words.jpg and hit enter.

Which function do I have to use to make those conversions from space to %20 , and all the other possible conversions i could need(which i can't think of any more, but i am pretty sure they exist, maybe on special symbols) ?

Use preg_replace:

$newUrl = preg_replace('/ /', '%20', 'http://test.com/two - words.jpg');

echo $newUrl;

OUTPUT

http://test.com/two%20-%20words.jpg

And alternatively str_replace:

$newUrl = str_replace(' ', '%20', 'http://test.com/two - words.jpg');

But more generally you will need to encode more than just the space. I made this function, if you don't want to use urlencode or rawurlencode, this is what you are looking for:

function encodeURI($URI)
{
    return str_replace(array('%', '^', '+', '{', '[', '}', ']', '"', '|', '\\', '<', '>', ' '),
        array('%25', '%5E', '%2B', '%7B', '%5B', '%7D', '%5D', '%22', '%7C', '%5C', '%3C', '%3E', '%20'), $URI);
}

example

echo encodeURI('http://test.com/two - ["word<><s.jpg');

OUTPUT

http://test.com/two%20-%20%5B%22word%3C%3E%3Cs.jpg