简体   繁体   English

使用PHP将%S中的SPACES替换为%20

[英]Using PHP Replace SPACES in URLS with %20

I'm looking to replace all instances of spaces in urls with %20. 我想用%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 : 这里不需要正则表达式,如果你只想用另一个字符串替换一段字符串:使用str_replace()应该绰绰有余:

$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. 但是,如果你想要更多,你可能会这样做,如果你正在使用URL,你应该看一下urlencode()函数。

Use urlencode() rather than trying to implement your own. 使用urlencode()而不是尝试实现自己的。 Be lazy. 偷懒。

I think you must use rawurlencode() instead urlencode() for your purpose. 我认为你必须使用rawurlencode()代替urlencode()。

sample 样品

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

With urlencode($str) will result 随着urlencode($ str)将导致

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

its not change to %20 at all 它根本不会改为%20

but with rawurlencode($image) will produce 但是使用rawurlencode($ image)会产生

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

You've got several options how to do this, either: 你有几个选择如何做到这一点,或者:

strtr()

Assuming that you want to replace "\\t" and " " with "%20" : 假设您要将"\\t"" "替换为"%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~ : 你在这里几乎没有选择,要么只更换空间~ ~ ,再替换空格和制表符~[ \\t]~各种空格 ~\\s~

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

Or when you need to replace string like this "\\t \\t \\t \\t" with just one %20 : 或者当你需要用一个%20替换像这个"\\t \\t \\t \\t"字符串时:

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 (   ) 我假设您真的想要使用手动字符串替换并处理更多类型的空格,例如不可破坏的空间(  

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

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

you may also consider using 你也可以考虑使用

$result = urlencode($yourstring)

to escape other special characters as well 也逃避其他特殊人物

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM