Using PHP Replace SPACES in URLS with %20

PhpRegexUrl

Php Problem Overview


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

Thank you!

Php Solutions


Solution 1 - Php

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() function.

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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 ( )

Solution 5 - Php

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

you may also consider using

$result = urlencode($yourstring)

to escape other special characters as well

Solution 6 - Php

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

    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - PhpPascal MARTINView Answer on Stackoverflow
Solution 2 - PhpMadara's GhostView Answer on Stackoverflow
Solution 3 - PhpdrosandaView Answer on Stackoverflow
Solution 4 - PhpVyktorView Answer on Stackoverflow
Solution 5 - Phpalex347View Answer on Stackoverflow
Solution 6 - PhpJonatas WalkerView Answer on Stackoverflow