I'm looking to replace all instances of spaces in urls with %20. How would I do that with regex?
Thank you!
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);
filter_var($url, FILTER_VALIDATE_URL), because it only validates if the URL starts with "http".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
http%3A%2F%2Fexample.com%2Fsome%20images.jpg , my server has some problems or your answer is inaccurate maybe ?! Thanks.+ - just not working.You've got several options how to do this, either:
urlencode() or rawurlencode() - functions designed to encode URLs for http protocolstr_replace() - "heavy machinery" string replacestrtr() - would have better performance than str_replace() when replacing multiple characterspreg_replace() use regular expressions (perl compatible)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 ( )
parse_urlto only apply functions on the parts you want to or (if possible) build a valid URL from the beginning.