Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP Replace SPACES in URLS with %20

Tags:

regex

url

php

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

Thank you!

like image 313
David Avatar asked Feb 11 '12 13:02

David


3 Answers

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.

like image 143
Pascal MARTIN Avatar answered Oct 15 '22 08:10

Pascal MARTIN


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

like image 33
Madara's Ghost Avatar answered Sep 18 '22 09:09

Madara's Ghost


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
like image 41
drosanda Avatar answered Oct 15 '22 09:10

drosanda