72

I'm looking to replace all instances of spaces in urls with %20. How would I do that with regex?

Thank you!

2
  • 1
    is there any specific reason why it has to be done with regex? if its a URL you could use php's urldecode method.. Commented Feb 11, 2012 at 13:26
  • You should better describe your problem. See parse_url to only apply functions on the parts you want to or (if possible) build a valid URL from the beginning. Commented Feb 11, 2012 at 13:42

6 Answers 6

108

No need for a regex here, if you just want to replace a piece of string by another: using str_replace() should be more than enough :

$new = str_replace(' ', '%20', $your_string);

But, if you want a bit more than that, and you probably do, if you are working with URLs, you should take a look at the [**`urlencode()`**][2] function.
Sign up to request clarification or add additional context in comments.

4 Comments

How to Replace # with / in codeignitor using routing.
I think this solution: stackoverflow.com/a/9240567/4027811 (actually below) is better, because change all critical signs for url, not only space.
Why is this replace even ":" and "/" from url? I'm having issues when trying to encode a URL to validate via filter_var($url, FILTER_VALIDATE_URL), because it only validates if the URL starts with "http".
This a terrible answer, str_replace comes with a lot of overhead. OP was looking to replace spaces in a URL, rawurlencode is the correct answer.
45

I think you must use rawurlencode() instead urlencode() for your purpose.

sample

$image = 'some images.jpg';
$url   = 'http://example.com/'

With urlencode($str) will result

echo $url.urlencode($image); //http://example.com/some+images.jpg

its not change to %20 at all

but with rawurlencode($image) will produce

echo $url.rawurlencode(basename($image)); //http://example.com/some%20images.jpg

4 Comments

This is usually the best answer to this question. Thanks!
For me, these outputs like this: http%3A%2F%2Fexample.com%2Fsome%20images.jpg , my server has some problems or your answer is inaccurate maybe ?! Thanks.
Best answer than the accepted. Saved my day and lote of code.
I have the same problem ad @adrianTNT, I really don't get it !
41

Use urlencode() rather than trying to implement your own. Be lazy.

5 Comments

He was, he asked instead of googling .)
Not lazy enough apparently :)
The only problem with this method is it turns all slashes and ampersands into entities also. My issue is only with spaces. Yours, Lazy.
This isn't the best answer to the question even for lazy: rawurlencode()
Well it replaces a space with + - just not working.
18

You've got several options how to do this, either:

strtr()

Assuming that you want to replace "\t" and " " with "%20":

$replace_pairs = array(
  "\t" => '%20',
  " " => '%20',
);
return strtr( $text, $replace_pairs)

preg_replace()

You've got few options here, either replacing just space ~ ~, again replacing space and tab ~[ \t]~ or all kinds of spaces ~\s~:

return preg_replace( '~\s~', '%20', $text);

Or when you need to replace string like this "\t \t \t \t" with just one %20:

return preg_replace( '~\s+~', '%20', $text);

I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space ( )

Comments

5
    public static function normalizeUrl(string $url) {
        $parts = parse_url($url);
        return $parts['scheme'] .
            '://' .
            $parts['host'] .
            implode('/', array_map('rawurlencode', explode('/', $parts['path'])));

    }

Comments

2
$result = preg_replace('/ /', '%20', 'your string here');

you may also consider using

$result = urlencode($yourstring)

to escape other special characters as well

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.