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

时间:2012-02-11 13:23:22

标签: php regex url

我希望用%20替换网址中的所有空格实例。我怎么用正则表达式做到这一点?

谢谢!

6 个答案:

答案 0 :(得分:74)

这里不需要正则表达式,如果你只想用另一个字符串替换一段字符串:使用str_replace()应该绰绰有余:

$new = str_replace(' ', '%20', $your_string);


但是,如果您想要更多,而且您可能会这样做,如果您正在处理URL,则应该查看urlencode()函数。

答案 1 :(得分:32)

使用urlencode()而不是尝试实现自己的。懒惰。

答案 2 :(得分:24)

我认为你必须使用rawurlencode()代替urlencode()。

样品

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

将使用urlencode($ str)

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

它根本不会改为%20

但是使用rawurlencode($ image)会产生

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

答案 3 :(得分:14)

你有多种方法可以做到这一点:

strtr()

假设您要将"\t"" "替换为"%20"

$replace_pairs = array(
  "\t" => '%20',
  " " => '%20',
);
return strtr( $text, $replace_pairs)

preg_replace()

这里你没有几个选项,只需替换空格~ ~,再替换空格和标签~[ \t]~或全部kinds of spaces ~\s~

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

或者当您需要使用"\t \t \t \t"替换%20之类的字符串时:

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

我假设你真的想要使用手动字符串替换并处理更多类型的空格,例如不可破坏空间( 

答案 4 :(得分:0)

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

你也可以考虑使用

$result = urlencode($yourstring)

也可以逃避其他特殊字符

答案 5 :(得分:0)

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

    }
相关问题