PHP replace spaces in urls image name

Looking to replace all instances of spaces in urls with %20? No need for a regex. Use rawurlencode() instead urlencode() for this purpose.
Example:

$img = 'your image.jpg';
$site   = 'http://www.example.com/'
$url   = $site.$img

urlencode($img) will result

echo $site.urlencode($img);
//output: http://www.example.com/your+image.jpg

It will not change to %20.

But with rawurlencode($img), it produce

echo $site.rawurlencode($img);
//output: http://www.example.com/your%20image.jpg

Another way of doing it is using str_replace

$url = $site.str_replace(' ', '%20', $img);

By Keenlio, July 21, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


one × = 8

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>